Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

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 asyncawait 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...