Amrmsmb
Amrmsmb

Reputation: 1

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

Upvotes: 0

Views: 1813

Answers (1)

Barremian
Barremian

Reputation: 31115

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>

Upvotes: 2

Related Questions