从 angular13 中的服务获取未定义的值

Getting an UNDEFINED value from services in angular13

**我在服务中使用 POST 方法函数并调用发送组件中的函数并将响应保存在服务变量中并将变量发送到接收组件并将数据分配给另一个变量但得到未定义的值我正在接收组件 **

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)
}

提前致谢

不推荐订阅服务,让服务returnobservable。此外,根据您的方法,您可以使用 subject 或类似的方法来通知您的 receiving 组件。

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();
   }
}

发送组件

constructor(private services:sharedservice) {}

ngOnInit() {
   this.formvalue()
}

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

接收组件

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