【问题标题】:Angular promise return角度承诺回报
【发布时间】:2018-03-05 03:26:37
【问题描述】:

我有一个 Angular 服务,我想返回一个带有类型数组的承诺,但我总是收到这个错误:src/app/city.service.ts(52,22): error TS2339: Property 'places'在“CityService”类型上不存在。 我不知道我做错了什么。

getPlace(coordinates : Coordinates) {
//    var places : Array<Place> = [];


let promise = new Promise((resolve, reject) => {

  this.http.get('http://localhost:3000/api/place/',  {params: coordinates})
      .toPromise()
      .then(

          res => { // Success
             var places: Array<Place>;

            this.places = res.results.map(item => {
              var place = new Place();
              place.place_id = item.place_id;
              place.name = item.name;
              place.vicinity = item.vicinity;
              place.coordinates = new Coordinates();
              place.coordinates.latitude = item.geometry.location.lat;
              place.coordinates.longitude = item.geometry.location.lng;
              return place;
            });

            resolve(this.places);
          },
          msg => { // Error
            reject(msg);
          }
      );
});
return promise;
}

【问题讨论】:

  • 您的服务是否有一个名为places 的字段,或者您的函数是否应该使用places 而不是this.places
  • 为什么要手动创建一个可观察的对象,在内部 http 解析时解析,在内部拒绝时拒绝?你为什么不直接使用 http 承诺?
  • @NoémiSalaün 菜鸟失误
  • @NoémiSalaün 如果我不想创建 observable,我可以使用内部 http 解析吗? codecraft.tv/courses/angular/http/http-with-promises
  • @John 请看下面我的回答

标签: angular typescript promise


【解决方案1】:

所以评论是非常正确的,不是服务的一部分,并且在函数内部声明的变量必须在没有 this 关键字的情况下调用。

 places = res.results.map ....

【讨论】:

  • 谢谢。我这里只有一个错误:places = res.results.map ....error TS2339: Property 'results' does not exist on type 'Object'。
【解决方案2】:

这是次要答案,只是关于不必要的承诺创建

这给出了相同的结果,而无需手动创建一个新的 Promise,该 Promise 在内部 Promise 解析时解析。它可以减少代码样板和更好的可读性。

getPlace(coordinates : Coordinates) {

    return this.http.get('http://localhost:3000/api/place/',  {params: coordinates})
        .toPromise()
        .then(res => {
            var places: Place[];

            places = res.results.map(item => {
              var place = new Place();
              place.place_id = item.place_id;
              place.name = item.name;
              place.vicinity = item.vicinity;
              place.coordinates = new Coordinates();
              place.coordinates.latitude = item.geometry.location.lat;
              place.coordinates.longitude = item.geometry.location.lng;
              return place;
            });

            return places;
        });

}

【讨论】:

  • 现在我有这个错误: src/app/city.service.ts(58,28) 中的错误:错误 TS2339:“对象”类型上不存在属性“结果”。
  • 我有这些导入:mport { HttpClient } from '@angular/common/http';从“@angular/common/http”导入 { HttpHeaders };从“@angular/common/http”导入 { HttpParams };从 'rxjs/operators' 导入 { catchError, map, tap };
  • 我的例子中可能有一个错字,因为我没有改变这部分的任何逻辑:/
  • 我会弄清楚的。非常感谢您的帮助!
猜你喜欢
  • 2023-04-02
  • 2016-07-07
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多