【问题标题】:How to make API response updates automatically in angular如何以角度自动更新 API 响应
【发布时间】:2022-01-21 09:52:33
【问题描述】:

API 模型包含不断在 API 中动态更新的 CPU 使用类别。但是当我刷新页面时,它只会更新数据,但可以在不刷新视图中的页面的情况下完成。 Setimeout 工作正常 除了 setTimeoutInterval 还有其他方法吗?

//app.service.ts


    private behaviourData = new BehaviorSubject<Model>(null);
    getBPmInfo(): Observable<Model>{
        return this.http.get<Model>(`${this.url}`).pipe(
          retry(3),
          tap(data => this.behaviourData.next(data))
        );
      }

//app.component.ts

model!: Model;
ngOnInit() {
getInformation(){
    this.bpmService.getBPmInfo().subscribe(data => {
      this.model = data;
    });
}
}

//app.component.html


    <div>
      <h1>CPU Usage{{model?.cpuUsage}}</h1>
    </div>

但是数据应该动态更新而不刷新页面。尝试使用 BehaviourSubject 我不知道为什么它不起作用。谁能帮我解决这个问题。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    你的服务方法应该只返回一个 Observable。如果你真的想使用一个 BehaviorSubject,它应该像这样在你的“app.component.ts”中定义:

    private behaviourData = new BehaviorSubject<Model>(null);
    public model$: Observable<Model>;
    
    constructor {
      this.model$ =  this.behaviourData.asObservable();
    }

    然后您应该关闭服务中的“tap(data => this.behaviourData.next(data))”并将其移至组件。

    最后,只需订阅你的 ngInit 中的 observable 并忘记像这样的“getInformation()”方法:

    ngOnInit() {
      this.bpmService.getBPmInfo().subscribe(data => {
        this.behaviourData.next(data)
      });
    }

    在您的模板中,您只需像这样使用“model$”可观察对象:

    <div>
      <h1 *ngIf="(model$ | async) as model">CPU Usage{{model.cpuUsage}}</h1>
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用 Interval(milliseconds) 来获取数据。用法:

      counter = interval(60000); // sets 60 seconds interval
      subscription: any = null;
      
      ngOnInit(): void {
      
         this.subscription = this.counter.subscribe(f => {
            this.bpmService.getBPmInfo().subscribe(data => {
        this.model = data;
         });
        })
       }
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2020-11-12
        • 2018-03-06
        • 2018-10-24
        • 2019-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多