1

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.

1
  • 1
    I feel like you're burrying the lead. The first part talks about there being an error. So why is there an error? What invalid json is trying to be parsed? Commented Dec 31, 2020 at 20:40

2 Answers 2

2

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); 
 });
}  
Sign up to request clarification or add additional context in comments.

Comments

1

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;
      }

Comments

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.