以下示例代码片段在教程中介绍如何执行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