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

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

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

note:

i tried

 {{ value | async }}

but still nothing gets displayed in the html template

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

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

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply