d-cubed
d-cubed

Reputation: 1112

Simplest example of using Angular 8 to convert http.get observable to string

I am using Angular to access values in Mongo through Express. I seem to be getting the correct responses from Express e.g. sending JSONs, arrays, or simple string values.

I can access those values using variables in console.log()when setting up the subscription. However, I am unclear on how to resolve that value as a variable that can be printed in console.log after the actual async\await call.

The Express URL /testmongothree returns a string. Accessing the same URL with:

basictest(){
  return this.http.get('testmongothree/',{responseType: 'text'}).subscribe(data => {
    console.log(data); 
 });
}  

results in 0) a console log for the string but only 1) a 'subscriber' notice from the console log after the async/await:

async basic_test() {
   let res = await this._apiService.basictest();
   console.log("console",res); 
  };

Looking at other Stack Overflow examples regarding Angular, Observables, and converting their values to strings, the examples here and here seemed most promising.

It seems that fundamentally this question shares problems with other similar questions - it is trying to make asynchronous functions work in synchronous contexts. Cf. here, here, and here.

The question then - what is the easiest way to delay the response of

console.log("console",res)

until the await has resolved?

[At the end of the day, this may be trying to shoehorn a round peg into a square hole.]

EDIT: I simplified the question to narrow the focus. Incorporating the suggestion from Andrei alleviated a confounding issue.

Upvotes: 1

Views: 807

Answers (2)

d-cubed
d-cubed

Reputation: 1112

The approach I have found so far - which is likely problematic is creating values that resolve observables and updating and returning those i.e.

basicinfo;  

basicobservable = this.http.get('testmongothree/', { responseType: 'text' }).subscribe(data => {
        console.log("api console", data);
        this.basicinfo = data;
      });
    
basictest() {
        this.http.get('testmongothree/', { responseType: 'text' }).subscribe(data => {
          console.log("api console", data);
          this.basicinfo = data;
        });
        return this.basicinfo;
      }

Upvotes: 1

Andrei
Andrei

Reputation: 12001

by default Angular will try to parse a response as JSON. to prevent that pass responseType: 'text' in options

basictest(){
  return this.http.get('testmongothree/', {responseType: 'text'}).subscribe(data => {
    console.log(data); 
 });
}  

Upvotes: 2

Related Questions