Gary
Gary

Reputation: 297

How to get string response from backend application with angular 7

I'm trying to get string response from my back application. i searched for this issue and almost in all the solutions they add { responseType: "text"} or {responseType: 'text' as 'json'} to get string, i added it but i can't arrive, here my angular code:

msg:any;
  func(){
    this.bookService.getRessource(url,{ responseType: "text"})
      .subscribe(data => {
        console.log(data)
        this.msg=data;
      }, err => {
        console.log(err)
      })
  }

This is my service, i have to add jwt to header:

getRessource(url,res){
   let headers=new HttpHeaders({'Authorization':'Bearer '+this.authService.jwt});
    return this.http.get(url,{headers:headers});
  }

The funtion add a book to user's favorite list, it works and add it to database but the weird thing is the error message is shown in the console and i can find the string that i would like to get in that error. But i can't comprehend how the function works and then the error message is shown!!

This is the error message i receive:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/user/addBookToUser?username=admin&id=9", ok: false, …}

Upvotes: 0

Views: 1568

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38827

In your current code, you are not placing responseType: text in the correct place. It needs to be an option of the actual HttpClient get() alongside headers:

msg:any;

func() {
  this.bookService.getRessource(url)
    .subscribe(data => {
      console.log(data)
      this.msg = data;
    }, err => {
      console.log(err)
    })
}

getRessource(url) {
  const headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.authService.jwt });
  const options = { responseType: 'text', headers };
  return this.http.get(url, options);
}

Hopefully that helps!

Upvotes: 4

Related Questions