如何从Angle的Observable / http / async调用返回响应?

JavaScript TypeScript

猪猪

2020-05-25

我有返回一个observable的服务,该服务向我的服务器发出一个http请求并获取数据。我想使用这些数据,但是我总是最终得到undefined有什么问题?

服务内容

@Injectable()
export class EventService {

  constructor(private http: Http) { }

  getEventList(): Observable<any>{
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get("http://localhost:9999/events/get", options)
                .map((res)=> res.json())
                .catch((err)=> err)
  }
}

零件:

@Component({...})
export class EventComponent {

  myEvents: any;

  constructor( private es: EventService ) { }

  ngOnInit(){
    this.es.getEventList()
        .subscribe((response)=>{
            this.myEvents = response;
        });

    console.log(this.myEvents); //This prints undefined!
  }
}

我检查了如何从异步调用返回响应?发布但找不到解决方案

第4166篇《如何从Angle的Observable / http / async调用返回响应?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
JinJin 2020.05.25

如果仅在模板中使用myEvents,则可以使用asyncPype。

在这里使用asyncPype和Angular4 HttpClient的示例https://stackblitz.com/edit/angular-rhioqt?file=app%2Fevent.service.ts

null 2020.05.25

这里的问题是,您刚好在块外执行操作时,您正在初始化this.myEventssubscribe()哪个异步块中。因此初始化之前调用console.log()subscribe()console.log()this.myEvents

请同时将您的console.log()代码移到subscribe()内,然后完成。

ngOnInit(){
    this.es.getEventList()
        .subscribe((response)=>{
            this.myEvents = response;
            console.log(this.myEvents);
        });
  }
柳叶风吹 2020.05.25

在angular / javascript中进行http调用是异步操作。因此,当您进行http调用时,它将分配新线程来完成此调用,并从另一个线程的下一行开始执行。这就是为什么您获得不确定的价值。因此,请进行以下更改以解决此问题

this.es.getEventList()  
      .subscribe((response)=>{  
       this.myEvents = response;  
        console.log(this.myEvents); //<-this become synchronous now  
    });
鱼二水 2020.05.25

结果不明确,因为角度过程异步。您可以尝试如下:

async ngOnInit(){
    const res = await this.es.getEventList();
    console.log(JSON.stringify(res));
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android