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

时间:2017-04-05 12:45:03

标签: angular typescript ionic2

我在details.ts文件的功能中从谷歌Api获取数据,我为此创建了服务,如下所示。它取代了Typescript错误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"
},

2 个答案:

答案 0 :(得分:2)

为此,您需要从Promise返回getTypeDetails

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 => {
});

答案 1 :(得分:1)

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

假设您的 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
   }
);