属性'then'在 ionic2 中的类型 'void' 上不存在



我正在details.ts文件的功能中从谷歌 API 获取数据,我为此创建了服务,如波纹管。 它的打字稿错误Property 'then' does not exist on type 'void'

this.typeApi.getTypeDetails(baseUrl).then(data => {
});

type-api.service.ts文件中,我从谷歌 API 获取数据作为波纹管,

import { Injectable } from '@angular/core';
import { Http /*, Response*/ } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TypeApi {
constructor(public http: Http ) {}
getTypeDetails(PlaceUrl){
this.http
.get(PlaceUrl)
.map(res => res.json())
.subscribe(
(data) => data,
(err) =>  err); // Reach here if fails
}
}

在 package.json 文件中,

"dependencies": {
"@angular/common": "2.4.8",
"@angular/compiler": "2.4.8",
"@angular/compiler-cli": "2.4.8",
"@angular/core": "2.4.8",
"@angular/forms": "2.4.8",
"@angular/http": "2.4.8",
"@angular/platform-browser": "2.4.8",
"@angular/platform-browser-dynamic": "2.4.8",
"@angular/platform-server": "2.4.8",
"@ionic-native/core": "3.1.0",
"@ionic-native/geolocation": "^3.4.4",
"@ionic-native/launch-navigator": "^3.4.4",
"@ionic-native/splash-screen": "3.1.0",
"@ionic-native/status-bar": "3.1.0",
"@ionic/storage": "2.0.0",
"font-awesome": "^4.7.0",
"ionic-angular": "2.3.0",
"ionic2-rating": "^1.2.0",
"ionicons": "3.0.0",
"rxjs": "5.0.1",
"sw-toolbox": "3.4.0",
"zone.js": "0.7.2"
},
"devDependencies": {
"@ionic/app-scripts": "1.1.4",
"typescript": "2.0.9"
},

要使其正常工作,您需要从类似getTypeDetails返回Promise

getTypeDetails(PlaceUrl){
return    this.http
.get(PlaceUrl)
.map(res => res.json())
.toPromise();
}

但只是归还Observable通常是更好的方法

getTypeDetails(PlaceUrl){
return    this.http
.get(PlaceUrl)
.map(res => res.json());
}

this.typeApi.getTypeDetails(baseUrl).subscribe(data => {
});

同意冈特,
此外,我建议您尽可能设置方法(函数)返回类型,以查看调用者将收到的结果类型。 对于上述护理:

假设您的TypeApi将在多个调用方中重用

public getTypeDetails(apiUrl: string) : Observable<any>{
return this.http.get(apiUrl)
.map(res => res.json())
.catch((error) => this.handleError(error));; 
}

handleError函数示例

private handleError (error: any) {
// Could dig deeper into the error to get a better message or use a remote logging infrastructure
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}

然后,当你调用此方法时,你必须订阅该方法将返回的结果:

this.typeApi.getTypeDetails(theUrl).subscribe(result => {
//here you have the analog success function from an ajax call 
//use the received data
}, 
error => {
//here you have the analog error function from an ajax call 
//treat the error
}
);

相关内容

  • 没有找到相关文章