Angular承诺回归

问题描述 投票:1回答:2

我有一个Angular服务,我想返回一个带有类型数组的承诺,但我总是得到这个错误:src / app / city.service.ts(52,22):错误TS2339:属性'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;
}
angular typescript promise
2个回答
3
投票

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

 places = res.results.map ....

1
投票

This is a secondary answer, just about the unnecessary promise creation

这给出了相同的结果,而不需要手动创建一个新的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;
        });

}
© www.soinside.com 2019 - 2024. All rights reserved.