1

When I'm trying to get data from api with this code:

getUserRole() {
      const headers = new Headers();
      headers.append('Authorization', `Bearer ${this.getToken()}`);
      console.log(this.getToken());
      const options = new RequestOptions({ headers: headers});
      return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`).pipe(map(res => res.json()))
      .subscribe(data => {
      this.userRole = JSON.stringify(data);
        if (this.userRole === 'parent') {
          this.logout();
      } else if (this.userRole === 'school') {
        this.isUser = true;
        this.isAdmin = false;
        this.cookieService.set('isSchool', '1');
      } else if (this.userRole === 'admin') {
        this.isUser = false;
        this.isAdmin = true;
        this.cookieService.set('isAdmin', '1');
      }
      });
   }

I get [], means blank array. But the same API when I try using postman, it gives the array filled like this:

[
    "Parent"
]

I doublechecked my api and confirmed, that everything seems ok, but I don't understand why I'm getting different result. Is there any problem with my approach?

1 Answer 1

1

Since angular6 has HttpClient by default, you dont have to call .json() explicitly

return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`).pipe(map(res => res))

also JSON.stringify is unecessary,

this.userRole = data;

EDIT:

You need to pass the headers in the put request aswell,

 return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options)
Sign up to request clarification or add additional context in comments.

6 Comments

Response {_body: "[]", status: 200, ok: true, statusText: "OK", headers: Headers, …} This is what I am receiving now. see these "[]".
which means your request is wrong! check the network tab and compare with the postman request
Got through, if you notice the code, I've forgot to put options header in get request.
yeah! glad to hear it, but certainly you need to make those changes mentioned in the answer. upvote if this helped
I already did and yeah that helped. Can you pl edit your answer to mention what I forgot?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.