0
votes

I am trying to pass some data inside observable function from several service to a non related component without using service call by using BehaviorSubject. However, not all of them work.

service.ts

export class Data{
 name:string;
 age:number;
 class:string;
 constructor(){
  this.name = "";
  this.age = null;
  this.class="";
 }
}
@Injectable()
export class InfoService {

 public myData = new Data();
 dataSubject = new BehaviorSubject<any>(this.myData);
 dataInfo = this.dataSubject.asObservable();

 constructor(private http:HttpClient){}
 getData(id:Id):Observable<any>{
  this.http.get(url+"id="+id).pipe(first()).subscribe(res=>{
    this.myData = res['data'];
    this.dataSubject.next(this.myData);
    console.log(this.myData);
  }
  return this.http.get(url+"id="+id);
}

I got the value from the console.log in the service file.

componenet.ts

export class Employee implements OnInit{

    constructor(public infoS:InfoService ){}

    ngOnInIt(){
        this.infoS.dataInfo.subscribe(res=>{
          console.log(res);
        }
    }
}

in the component file, the console.log give me an empty Data object. And I check the inspect console, The component line run before the service line run. Is there any way I can set the component run after the service run? In addition, as I mentioned it in the beginning, some of them are working. And the console shows that the working one has the component line run before and after the service line. So the working one, the component line actually run twice, one is before the service line, and one after that makes it work.

2
Which version of Angular you are using? - AlokeT
where will you call your getData() method of service in component? - GaurangDhorda
why dont you subscribe to behavior subject directly? currently you have subscribed to dataInfo instead of dataSubject - Mustahsan
I am using angular 8. And the getData() is at a different component with the service component. There is no relation between - AshH

2 Answers

1
votes

dataInfo will get value of behavior subject for only first time, and will not be updated whenever behavior subject is updated, so you need to subscribe to dataSubject behavior subject directly:

ngOnInIt(){
   this.infoS.dataSubject.subscribe(res=>{
          console.log(res);
   }
}
0
votes

Try doing the following:


this.infoS.dataInfo.subscribe(res=>{
   if(res) {
       console.log(res);
   }
}