简体   繁体   English

如何将 observable 的值从服务传递到组件以更新模板

[英]How to pass value of observable from a service to component to update the template

in the below code i am trying to display the value returned from observables.在下面的代码中,我试图显示从 observables 返回的值。 the observable function which returns the value is created in a service as shown below in the code.返回值的可观察 function 在服务中创建,如下面的代码所示。

in the manin component, as shown below, i access that method from the service object and assign the supposed returned value to a variable.在 manin 组件中,如下所示,我从服务 object 访问该方法并将假定的返回值分配给一个变量。 that variable is linked to the template via interpolation as seen in the template section below.该变量通过插值链接到模板,如下面的模板部分所示。

the problem i am facing is, when i run the code, the value does not get passed from the service to the component and consequently there is no change occure in the template我面临的问题是,当我运行代码时,值不会从服务传递到组件,因此模板中没有发生任何变化

please let me know how to correct the code so the template gets updated with the right value from the observables in the service请让我知道如何更正代码,以便使用服务中的 observables 中的正确值更新模板

component : value: void;组件:值:无效;

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

} }

service :服务

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 .html

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

note :注意

i tried我试过了

 {{ value | async }}

but still nothing gets displayed in the html template但 html 模板中仍然没有显示任何内容

You aren't returning anything from the function in service.您没有从服务中的 function 返回任何东西。

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

And use async pipe in the component并在组件中使用async pipe

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM