Trying to pass data inside an observable function from multiple services to an unrelated component without using service calls by utilizing BehaviorSubject has yielded mixed results.
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);
}
The value from the console.log in the service file was obtained successfully.
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 gives an empty Data object. Upon inspecting the console, it was noticed that the component line runs before the service line. Is there a way to ensure the component runs after the service? Furthermore, some instances are working correctly. The console indicates that in the successful cases, the component line executes both before and after the service line. Therefore, for those that work, the component line actually runs twice - once before the service line and once after, leading to success.