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.
getData()
method of service in component? - GaurangDhorda