将Promise <any>转换为特定类型的错误

时间:2019-06-03 09:16:35

标签: angular typescript ionic4

打字稿/ angular4 + / ionic4的新手问题。我实现了一项服务,该服务将进行后端REST调用,并根据调用的响应将获取的信息存储到本地存储中。 之所以在本地存储中,是因为这样我以后可以查询相同的内容。我似乎收到类型转换错误。任何线索都会有所帮助。

 this.locationService.saveLocationNew(this.newLocation).subscribe(res=> {
     this.locationInfo = res;
     console.log('Response from backend'+ this.locationInfo);
     this.storage.set(StorageKeys.LOCATION_DATA, this.locationInfo);
     this.locationInfo = null;
     this.locationInfo = <AddLocationResponse>this.storage.get(StorageKeys.LOCATION_DATA); --> this is where I see the type conversion error.
   });

我的服务如下

 saveLocationNew(request: AddLocationData): Observable<AddLocationResponse> {
      return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request , { headers: Constants.createHeader()}); --> I don't use a then and map res to res.json ; since that is not needed in Ionic4
 }

2 个答案:

答案 0 :(得分:1)

尝试这个

 this.locationService.saveLocationNew(this.newLocation).subscribe(async (res)=> {
     this.locationInfo = res;
     console.log('Response from backend'+ this.locationInfo);
     this.storage.set(StorageKeys.LOCATION_DATA, this.locationInfo);
     this.locationInfo = null;
     const res = await <AddLocationResponse>this.storage.get(StorageKeys.LOCATION_DATA).catch((err) => 'return anything you want');
     if (res) {
       this.locationInfo = res;
     }
   });

答案 1 :(得分:0)

使用TypeError检查类型

function determineIfIsAnimalOrHuman(toBeDetermined: PersonOrAnimal): toBeDetermined is Animal {
  if((toBeDetermined as Animal).type){
    // do some thing
  }
   throw new TypeError('Object is no Animal');
}