我想使用Promise运算符
首先我加入了rxjs:
import 'rxjs/add/operator/toPromise';
然后在我的组件中,我用它
ngOnInit() {
this.EJnames= this.dataservice.getResults();
this.generalinfosservice.getResults("nothing").then(data=>{this.data=data; console.log(data)}); //Log 1
console.log(this.data); // log 2
}
我收到了这个错误
ERROR TypeError: this.generalinfosservice.getResults(...).toPromise is not a function
我已经检查过Package.json我有rxjs:
"rxjs": "^5.1.0",
这是generalinfosservice.getresults
功能
import { Injectable } from '@angular/core';
import { RmpmService} from '../../shared/abstract-classes/service'
import { HttpClient } from '@angular/common/http';
@Injectable()
export class GeneralinfosService extends RmpmService {
constructor(public httpClient: HttpClient) { }
public getResults(body) {
let url;
let mockUrl
url = '/obtenirNomenclatures/typeNomenclatures/';
mockUrl = 'assets/data/group.json';
return this.post(url, mockUrl, body);
}
}
并发布一个抽象类中的函数:
post( url, mockUrl, body) {
if( environment.mocked ) {
return this.httpClient.get( mockUrl ).toPromise().then( data => { return data} );
} else {
return this.httpClient.post( url, JSON.stringify( body ) )
.toPromise()
.then( data => {
return data;
}, ( err: any ) => {
return this.handleError( err.message );
} );
}
}
PS:我在嘲笑环境
答案 0 :(得分:-1)
您在this.post()
中呼叫getResults()
。这将在您的班级(GeneralInfoService
)中查找名为post()
的方法。
您实际需要致电的是this.httpClient.post()
。
答案 1 :(得分:-1)
// Need to import this for my fixes below to work:
import { Observable } from 'rxjs/Observable';
// Your current "post" method.
post( url, mockUrl, body) {
if( environment.mocked ) {
// In your promise, you are not returning another promise. You are returning only the "data" value, which doesn't have a ".then()" function associated to it.
// return this.httpClient.get( mockUrl ).toPromise().then( data => { return data} );
// Here is how you should do it:
return this.httpClient.get( mockUrl )
.toPromise()
.then(( data ) => Observable.of( data ).toPromise());
} else {
return this.httpClient.post( url, JSON.stringify( body ) )
.toPromise()
.then(
( data ) => Observable.of( data ).toPromise(),
( err: any ) => this.handleError( err.message )
);
}
}