角度:订阅后不更新变量

时间:2020-05-27 19:07:01

标签: angular

我有一个服务,返回了Observables<SubscriberModel[]>

export interface SubscriberModel {
    email: string;
}

在我的组件中,我在构造函数中获得了Subscriber $

public subscribers$: Observable<SubscriberModel[]>;
this.subscribers$ = this.subscribersService.getAll();

并在模板中显示它们:

<p *ngFor="let subscriber of subscribers$ | async">{{subscriber.email}}</p>
<button (click)="onDownloadClick()">
    <a [href]="fileUrl" download="file.txt">DownloadFile</a>
</button>

我必须将订户下载到文件中:

public data: any;

public onDownloadClick(): void {
    this.subscribers$.pipe(
        map(res => res.map(i => i.email)),
    )
        .subscribe(res => {
            console.log(res) //array of string
            this.data = res;
        });

    console.log(this.data); //undefined
    const blob: Blob =
        new Blob([this.data], {type: 'application/octet-stream'});

    this.fileUrl =
        this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}

为什么在console.log this.data中未定义?

2 个答案:

答案 0 :(得分:4)

将您的过程相关服务的订阅放入其中。异步功能不会停止其他进程。因此,代码仍在执行的同时在下一行继续进行。因此异步功能之外的数据可能由于服务器的响应而无法读取数据。

public onDownloadClick(): void {
   this.subscribers$.pipe( map(res => res.map(i => i.email)),)
   .subscribe(res => {
       console.log(res) //array of string
       this.data = res;
       console.log(this.data); //undefined
       const blob: Blob = new Blob([res], {type: 'application/octet-stream'});       
       this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
    });

}

答案 1 :(得分:2)

this.data被异步分配数据。因此,所有从属语句必须在预订中。因此,console.log应该在订阅中

public data: any;

public onDownloadClick(): void {
  this.subscribers$.pipe(
    map(res => res.map(i => i.email)),
  )
  .subscribe(res => {
    console.log(res) //array of string
    this.data = res;
    console.log(this.data);
    const blob: Blob = new Blob([this.data], {type: 'application/octet-stream'});
    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
  });
}

有关访问异步数据的更多信息:https://stackoverflow.com/a/14220323/6513921