我是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);
}
}
如何修复此错误?
谢谢您,
汤姆
最佳答案
一个可观察到的事物并没有像then
这样的承诺方法。在您的服务中,您正在执行一个http调用,该调用返回一个observate,并将这个observate映射到另一个observate。
如果你真的想使用promise风格的api,你需要使用toPromise
操作符将你的observate转换成promise。默认情况下,此运算符不可用,因此您还需要在项目中导入一次。
import 'rxjs/add/operator/toPromise';
使用promises是可以的,但是有一些很好的理由可以直接使用可观察的api。有关详细信息,请参见本blog post关于使用可观测数据的广告。
如果您想直接使用Observable API,那么用
then
调用替换subscribe
调用。但是请记住,当您的组件被销毁时,每个订阅都需要取消。getConnections(): void {
this.subscription = this.connectionService.getConnections()
.subscribe(connections => this.connections = connections);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
使用Observables时的另一个选项是将结果Observable赋给组件中的字段,然后使用
async
pipe。这样,angular将为您处理订阅。