Service, promise

0

Mam taki service:

  return this.http
      .post('http://localhost:61862/api/Account/Register', JSON.stringify(data), {headers: headers})
      .toPromise()
      .then((res) => { res.json() }, (error) => { console.log(error.json().Message) });

Wprowadzam błędne dane i wyświetla mi w konsoli: The request is invalid.

Natomiast gdy wywołuję ten serwis i chcę odebrać dane (czyt. wiadomość o błędzie):

this._userService.setUser(email, password).then(res => {
        console.log(res); // undefined
      }, (error) => {
        console.log(error);// <-- ?
      });

Zwraca res jako undefined i wchodzi do 1 bloku, a nie do 2. W czym jest problem?

0

No bo zwracasz tam undefined w serwsie, jak chcesz przekazać błąd dalej to albo wywal tego console.loga (bo docelowo to śmieć) albo rzuć błedem tam ponownie (no bo teraz masz za tym sukces bo "obsłużyłeś" błąd).

return this.http
  .post('http://localhost:61862/api/Account/Register', JSON.stringify(data), {headers: headers})
  .toPromise()
  .then(res => res.json())
;

lub

return this.http
  .post('http://localhost:61862/api/Account/Register', JSON.stringify(data), {headers: headers})
  .toPromise()
  .then(res => res.json()) // <- tu nic nie zwracałeś przez te klamry, jak klamry to `return`
  .catch(error => {
    console.log(error.json().Message); // <- to zwraca undefined
    throw error;
  })
;
0

Chodziło mi że bez console.log i tak nie wyrzuca tego błędu i wskazuje na undefined. Tak czy owak działa. Dziękuje za pomoc. :-)

1 użytkowników online, w tym zalogowanych: 0, gości: 1