Angular2 Promise返回undefined

时间:2017-10-18 09:02:36

标签: javascript angular

我的承诺有问题。我不知道为什么但它确实会回归" undefined"在调用我的API之后在组件中。

送货员:

export class DeliveryMan {
  id: number;
  mail: string;
  passwordToInitialize: boolean;

  name: string;
  administrator: boolean;
}

组件:

export class AdminComponent implements OnInit {

    tabDeliveryMan = [];

    constructor(private deliveryManService: DeliveryManService) {}

    ngOnInit(): void {
        this.deliveryManService.getAll()
          .then((tabDeliveryMan) => {
            this.tabDeliveryMan = tabDeliveryMan,
            console.log(tabDeliveryMan)
        });
    }

    [...]
}

deliveryManService:

export class DeliveryManService {
    getAll(): Promise<DeliveryMan[]> {
      const url = this.apiUrl + 'getAllDeliveryMan';
      return this.http.get(url)
        .toPromise()
        .then((response) => response.json() as DeliveryMan[])
        .catch(this.handleError);
    }

    [...]
}

我得到一个未定义的日志,但我的回答不是空的:

Response {_body: "[{"id":1,"mail":"antoine@mail.com","password":"89c…ze":true,"name":"antoine","administrator":false}]", status: 200, ok: true, statusText: "OK", headers: Headers, …}

1 个答案:

答案 0 :(得分:0)

感谢评论,我解决了我的问题。取而代之:

.then((response) => response.json() as DeliveryMan[])

由此

response => response.json()