【问题标题】:How to pass value of observable from a service to component to update the template如何将 observable 的值从服务传递到组件以更新模板
【发布时间】:2021-06-22 02:27:07
【问题描述】:

在下面的代码中,我试图显示从 observables 返回的值。返回值的可观察函数是 在服务中创建如下代码所示。

在 manin 组件中,如下所示,我从服务对象访问该方法并将假定的返回值分配给 一个变量。该变量通过插值链接到模板,如下面的模板部分所示。

我面临的问题是,当我运行代码时,值不会从服务传递到组件,因此 模板没有变化

请告诉我如何更正代码,以便使用服务中可观察对象的正确值更新模板

组件: 值:无效;

constructor(private myservice: MyService1Service) {}
ngOnInit(){
this.todaydate2 = this.myservice.showTodayDate();
this.value = this.myservice.observablesTest();

}

服务

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable, Observer } from 'rxjs';



@Injectable({
  providedIn: 'root'
})
export class MyService1Service {
  name : string;
  obsValue: Observable<unknown>;
  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
        this.name = params['name'];
    });
  }
  showTodayDate() {
    let ndate = new Date();
    return ndate;
 }
  observablesTest() {
   this.obsValue = new Observable((observer) => {
    console.log("Observable starts")
    setTimeout(() => { observer.next("3000") }, 1000);
   });
  }
}

.html

<b>todayDate is: {{todaydate2}}</b>
<b>observableValue is: {{value}}</b>

注意

我试过了

 {{ value | async }}

但 html 模板中仍然没有显示任何内容

【问题讨论】:

  • {{ value | async }}怎么办
  • @Emilien 仍然没有显示任何内容

标签: javascript node.js angularjs angular observable


【解决方案1】:

您没有从服务中的函数返回任何内容。

observablesTest(): Observable<any> {
  this.obsValue = new Observable((observer) => {
    console.log("Observable starts")
    setTimeout(() => { 
      observer.next("3000");
      observer.complete(); 
    }, 1000);
  });
  return this.obsValue;     // <-- return here
}

并在组件中使用async管道

<b>observableValue is: {{ value | async }}</b>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2021-02-02
    • 2018-09-03
    • 1970-01-01
    • 2017-04-11
    • 2018-01-19
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多