Jenuel Ganawed
Jenuel Ganawed

Reputation: 384

How to set a type for data received from Angular HTTP request?

This is my code to fetch data:

login() {
    const url = api + 'login';
    this.http.post(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }

This would return a JSON of

{
   message: "logged In Successful!",
   token: "e4affa4633fb046333731ae6fadcb980b98636b513a0fb80721759267b4efa5c9b7845663f2b1288"
}

It works, it saves to the local storage, but this error keeps popping in my console? why?

enter image description here

Upvotes: 1

Views: 782

Answers (1)

cyr_x
cyr_x

Reputation: 14267

You're getting the error because typescript cannot resolve a type for the response object, therefore you need to specify the response object type of your post request:

  login() {
    const url = api + 'login';
    this.http.post<{ message: string, token: string }>(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }

Upvotes: 4

Related Questions