【问题标题】:I am unable to assign subscribed values to a variable in a component. How can I do that?我无法将订阅的值分配给组件中的变量。我怎样才能做到这一点?
【发布时间】:2020-07-29 13:08:03
【问题描述】:

考虑:

this.getList().subscribe((data) => {
  console.log("data", data);
  this.listItems = data;});

以上是我从中返回可观察对象的方法。

【问题讨论】:

标签: angular rxjs


【解决方案1】:

试试这个,将 observable 分配给组件属性

listItems$ = this.getList();

然后使用异步管道订阅模板中的 observable。

<ng-container *ngIf="listItems$ | async as listItems">
  {{ listItems | json }}
</ng-container>

无需管理订阅。

【讨论】:

    【解决方案2】:

    上述方法应该有效。我建议在分配后记录 this.listItems 以仔细检查您是否不确定。

    您可能遇到的问题是它的运行顺序。请记住,这是异步发生的,所以 listItems 会在所有其他正常组件发生后被分配。

    我经常使用的一个解决方案(假设您的模板引用了数据)是将整个模板(或无论如何使用数据的区域)保存在 ngIf 中:

    *ngIf="this.listItems"
    

    这样模板只有在订阅完成后才会显示。

    【讨论】:

      【解决方案3】:

      推荐的方式是不要订阅内部组件类(.ts),而是使用可观察的。

      listItems$ = this.getList(); // I agree with Adrian Brand
      

      模板:(假设您使用表格)

      <table>
          <tr *ngFor="let item of listItems$ | async;">  // async handles unsubscribe by itself.
           <td>{{ item.name }}</td>
          </tr>
      <table>
      

      如果出于某种原因想订阅模板,那么不要忘记取消订阅,例如:

      const listSubcription = this.getList().subscribe((data) => {
        this.listItems = data;});
      
      ngOnDestroy() {
       listSubcription.unsubscribe();
      }
      

      【讨论】:

        【解决方案4】:
        // Here is sample code 
        // Componet Name: list.component.ts
        
        import { HttpClient } from '@angular/common/http';
        import { Component, OnInit } from '@angular/core';
        import { NgZone} from '@angular/core';
        import {HttpServiceService} from './../http-service.service';
        
        @Component({
          selector: 'app-list',
          templateUrl: './list.component.html',
          styleUrls: ['./list.component.scss']
        })
        export class ListComponent implements OnInit {
        
          constructor(
             private http: HttpServiceService,
             private zone: NgZone
            ) { }
          brews: object;
          ngOnInit(): void {
              this.http.getPeople().subscribe(data => {
              this.brews = data;
              alert(JSON.stringify(this.brews));  // Diplay 
              console.log(this.brews);
              });
          }
        }
        
        // Here is my http service
        // Componet Name: list.component.ts
        
        import { Observable, of } from 'rxjs';
        import { Injectable } from '@angular/core';
        
        @Injectable({
          providedIn: 'root'
        })
        export class HttpServiceService {
        
          constructor() { }
          getPeople(): Observable<any>{
            const peopleArray = [{
              firstName: 'Al',
              lastName: 'Moje',
              age: 63
            }];
            return of(peopleArray);
         }
        }
        
           
        

        【讨论】:

          猜你喜欢
          • 2022-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-05
          • 1970-01-01
          • 2012-08-18
          • 1970-01-01
          • 2015-10-25
          相关资源
          最近更新 更多