订阅调用后的空数组

Ale*_*lex 0 angular

我写了一个服务:

loadroom() : Observable<any[]>{
    return this.http.get(this.roomUrl)
        .pipe(
            map((response: any) => {
                let resources = response;
                return resources.map(function(room:any) {
                    return {id: room.id, title: room.title, eventcolor: room.eventColor};
                });
            })
        );
}
Run Code Online (Sandbox Code Playgroud)

然后我在一个组件中使用这个服务

rooms: any[] = [];       
ngOnInit() {
    this.schedulerService.loadroom().subscribe(response => this.rooms = response);
    console.log(this.rooms);
}
Run Code Online (Sandbox Code Playgroud)

我没有看到数组中的数据。在控制台中,我得到一个空数组 []

但如果我使用

this.schedulerService.loadroom().subscribe(response => {console.log(response)});
Run Code Online (Sandbox Code Playgroud)

我得到数据。

小智 5

是的,这完全是预期的行为,subscribe是异步的,这意味着调用它不会阻止代码的执行,它不会在执行下一行之前等待它完成。所以

this.schedulerService.loadroom().subscribe(response => this.rooms=response);
    console.log(this.rooms);
Run Code Online (Sandbox Code Playgroud)

订阅完成前触发日志