订阅呼叫后为空数组

时间:2019-07-23 13:22:30

标签: 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};
                });
            })
        );
}

然后我在组件中使用此服务

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

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

但是如果我使用

this.schedulerService.loadroom().subscribe(response => {console.log(response)});

我得到了数据。

3 个答案:

答案 0 :(得分:4)

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

this.schedulerService.loadroom().subscribe(response => this.rooms=response);
    console.log(this.rooms);

在订阅完成之前触发日志

答案 1 :(得分:0)

订阅是异步的。执行可能没有完成:您需要处理链式事件以保持流程在这一点上。您需要对FileNotFoundError Traceback (most recent call last) <ipython-input-1-1bae56973fdf> in <module> 12 try: ---> 13 data = codecs.open(name, encoding='utf-8', errors='strict') 14 for line in data: ~\AppData\Local\Continuum\anaconda3\lib\codecs.py in open(filename, mode, encoding, errors, buffering) 896 mode = mode + 'b' --> 897 file = builtins.open(filename, mode, buffering) 898 if encoding is None: FileNotFoundError: [Errno 2] No such file or directory: 'plaintext1.txt' During handling of the above exception, another exception occurred: NameError Traceback (most recent call last) <ipython-input-1-1bae56973fdf> in <module> 17 pass 18 print (data + "is valid UTF") ---> 19 except UnicdeDecodeError: 20 print (data + "invalid UTF") 21 NameError: name 'UnicdeDecodeError' is not defined 进行的所有操作都必须在订阅事件中。

答案 2 :(得分:0)

这是因为Observable是异步的。意味着console.log(this.rooms);之前 response => this.rooms=response发生。

所以使用它的正确方法是:

this.schedulerService.loadroom().subscribe(response => {
  this.rooms = response;
  console.log(this.rooms);
});