2022-05-29

Cannot set service data inside subscribe in Angular

I want to set shared service data inside subscribe method my page structure is enter image description here

i have to access data set from one component app.component in home component and header component.

 this.sharedService.setData({title: this.title, logo: this.logo});

app.component.ts

  setData(): void {
    this.http.get(this.baseUrl+'api/content').subscribe(result  => {
      this.title=result['response'].title;
      this.logo=result['response'].logo;
      this.sharedService.setData({title: this.title, logo: this.logo});
    }); 
    
  }

but in this case service data is set when i access it in any other component getting blank data for title and logo but when i pass static data (Not is subscribe method API call) then it's value is getting passed to other components.

Service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { BehaviorSubject } from 'rxjs';

export interface SharedData {
  title: string;
  logo: string;

}

@Injectable({
  providedIn: 'root'
})

export class SharedService  {

  private sharedData$ = new BehaviorSubject<SharedData>({title: '', logo: ''});
  sharedData = this.sharedData$.asObservable();

  constructor() { }

  setData(data: SharedData): void {
    this.sharedData$.next(data);
  }
}

Any Solution Thanks



No comments:

Post a Comment