Search code examples
angularservice

Getting an UNDEFINED value from services in angular13


**Iam using a POST method function in service and calling the function in sendingcomponent and saving the response in service variable and sending the variable to receivingcomponent and assigning the data to another variable but getting an undefined value i receivingcomponent **

sending.component.ts

import{sharedservice}....
constructor(private services:sharedservice)
ngOnInit(){
this.formvalue()
}
this.formvalue(){
this.services.getdata(this.form.value)
}

shared.services.ts

import{Httpclient}....
@Injectable()
dataofservice:any;
constructor(private http:httpClient)
this.getdata(data:any){
this.http.post('http://localhost:3002/data')
.subscribe(res =>{
this.dataofservice= res   
console.log(this.dataofservice) -->(here I am getting the value)
})
}

receiving.component.ts

import{sharedservice}....
constructor(private services:sharedservice)
datatostore:any;
ngOnInit(){
this.datatostore = this.services.dataofservice  
console.log(this.datatostore)-->(here I am getting value as UNDEFINED)
}

Thanks in advance


Solution

  • I don't recommend subscribing in the service, let the service return the observable. Also, based on your approach, you could use a subject or similar in order to notify your receiving component once your reach it.

    import{Httpclient}....
    @Injectable()
    export class YourService {
       private dataofservice = new BehaviorSubject<any>({});
      
       constructor(private http: httpClient)
       
       this.getdata(data: any): Observable<any> {
          return this.http.post('http://localhost:3002/data').pipe(
             tap(response => this.dataofservice.next(response))
          );
       })
    
       getDataOfService(): Observable<any> {
          return this.dataofservice.asObservable();
       }
    }
    

    sending component

    constructor(private services:sharedservice) {}
    
    ngOnInit() {
       this.formvalue()
    }
    
    formvalue() {
      this.services.getdata(this.form.value)
       .subscribe(console.log); // your data is here
    }
    

    receiving component

    ...
     constructor(private services:sharedservice) {}
       
      ngOnInit() {
        this.services.getDataOfService(data)
         .subscribe((response) => console.log(response)) // and here as well
      }