以下示例代碼片段在教程中介紹如何執行JQuery getJSON()調用,然後將JQueryXHR導致一個Promise,然後轉換爲Observable。TypeScript:錯誤TS2345:類型'JQueryXHR'的參數不可分配給類型爲'Promise <any>'的參數'
/// <reference path="../typings/tsd.d.ts" />
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `
<input id="search" type="text" class="form-control">
`
})
export class AppComponent {
example(searchTerm: string) {
let url: string =
"https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
let jqueryXhr: JQueryXHR = $.getJSON(url);
let observable: Observable<any> = Observable.fromPromise(jqueryXhr);
}
}
這個例子沒有工作在運行,但TSC編譯器會引發以下錯誤:
app/app.component.ts(28,61): error TS2345: Argument of type 'JQueryXHR' is not assignable to parameter of type 'Promise<any>'.
Types of property 'then' are incompatible.
有沒有乾淨的方式投或轉換JQueryXHR對象的承諾,或另一種類型,那可以轉換成Observable?
%的誤差,該類型的財產「那麼」不兼容,從而導致錯誤使用隱性或顯性的轉換。但是,使用你的Promise.resolve()的建議工作,並且這滿足了編譯器。感謝你的回答。 –
是的,這是dables和promises之間的區別 - 在後者中,then方法的返回值及其回調很重要。 – Bergi