【发布时间】:2017-02-07 03:27:21
【问题描述】:
以下示例代码 sn-p 在教程中介绍了如何执行 JQuery getJSON() 调用,然后将 JQueryXHR 结果转换为 Promise,然后将其转换为 Observable。
/// <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 对象转换或转换为 Promise 或其他可以转换为 Observable 的类型?
【问题讨论】:
标签: jquery typescript promise observable