简体   繁体   中英

Angular2 Promise returning undefined

I have a problem with my Promise. I don't know why but it does return "undefined" in the component after calling my API.

DeliveryMan:

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

  name: string;
  administrator: boolean;
}

Component:

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

    [...]
}

I get a log undefined but my response isn't null :

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

Thanks to the comment i resolved my problem. Replacing this :

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

by this

response => response.json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM