Goldbones
Goldbones

Reputation: 1447

Get string response from Observable

I´m retrieving a String from backend:

String value = "{I am here}";

On my service:

getValue(): Observable<String> {
    return this.http.get<String>(this.myURL);
  }

On my component I´m subscribing:

String myMessage;

  getValue(): void {
    this.myService.getValue()
    .subscribe(message=> {
        this.myMessage= myMessage;
        console.log("WHY NOT ENTER HERE?)

);
  });

What I´m doing wrong for not even getting the message from console.log?

Upvotes: 2

Views: 1096

Answers (2)

Ngoc Nam Nguyen
Ngoc Nam Nguyen

Reputation: 513

I guess you need to be specific about the responseType if you want to use string.

Here is the doc https://angular.io/guide/http#requesting-non-json-data

In your case, the getValueshould do this:

return this.http.get(this.myURL, { responseType: 'text' });

Note that you don't need to use <string>

Upvotes: 5

Seah Sky
Seah Sky

Reputation: 154

From what I see, there is a mistake in your code, probably the reason you can't assign any value to myMessage:

Your code:

String myMessage;

  getValue(): void {
    this.myService.getValue()
    .subscribe(message=> {
        this.myMessage= myMessage;
        console.log("WHY NOT ENTER HERE?)

);
  });

It should be:

String myMessage;

  getValue(): void {
    this.myService.getValue()
    .subscribe(message=> {
        this.myMessage= message;
        console.log("WHY NOT ENTER HERE?)

);
  });

Notice the value assignment part in the callback function, you've used the wrong variable.

Hope it helps.

Upvotes: 0

Related Questions