[Fixed] 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. the observable function which returns the value is
created in a service as shown below in the code.

in the manin component, as shown below, i access that method from the service object and assign the supposed returned value to
a variable. 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

value: void;

constructor(private myservice: MyService1Service) {}
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';

  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);


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


i tried

 {{ value | async }}

but still nothing gets displayed in the html template


You aren’t returning anything from the function in service.

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

And use async pipe in the component

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

Leave a Reply

(*) Required, Your email will not be published