我是 angular 2 的新手,我正在尝试发出 REST GET 请求,但在尝试时出现此错误:
error TS2339: Property 'then' does not exist on type 'Observable<Connection[]>'.
这是调用服务的组件:
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Connection } from './connection';
import { ConnectionService } from './connection.service';
let $: any = require('../scripts/jquery-2.2.3.min.js');
@Component({
selector: 'connections',
styleUrls: [ 'connections.component.css' ],
templateUrl: 'connections.component.html',
providers: [ConnectionService]
})
export class ConnectionsComponent implements OnInit {
connections: Connection[];
selectedConnection: Connection;
constructor(
private connectionService: ConnectionService,
private router: Router) { }
getConnections(): void {
this.connectionService.getConnections().then(connections => {
this.connections = connections;
});
}
ngOnInit(): void {
this.getConnections();
}
onSelect(connection: Connection): void {
this.selectedConnection = connection;
}
gotoDetail(): void {
this.router.navigate(['/connectiondetail', this.selectedConnection.id]);
}
}
这是连接服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Connection } from './connection';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ConnectionService {
private connectionsUrl = 'https://localhost/api/connections'; // URL to web API
constructor (private http: Http) {}
getConnections(): Observable<Connection[]> {
return this.http.get(this.connectionsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
如何修复此错误?
谢谢,
汤姆
最佳答案
Observable 没有像 then
这样的类似 promise 的方法。在您的服务中,您正在执行一个返回 Observable 的 http 调用,并将此 Observable 映射到另一个 Observable。
如果您真的想使用 promise 风格的 API,您需要使用 toPromise
运算符将您的 Observable 转换为一个 promise。该运算符默认不可用,因此您还需要在项目中导入一次。
import 'rxjs/add/operator/toPromise';
使用 promises 没问题,但有一些很好的理由直接使用 Observable API。详情请看这个blog post宣传 Observables 的使用。
如果您想直接使用 Observable API,请将您的 then
调用替换为 subscribe
调用。但请记住,当您的组件被销毁时,每个订阅也需要取消。
getConnections(): void {
this.subscription = this.connectionService.getConnections()
.subscribe(connections => this.connections = connections);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
使用 Observable 的另一个选择是将生成的 Observable 分配给组件中的一个字段,然后使用 async
pipe .这样一来,Angular 将为您处理订阅。
关于angular - Observable 类型不存在属性 'then',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985605/