**Iam在服务中使用POST方法函数,调用sendingcomponent中的函数,保存服务变量中的响应,并将该变量发送给receivingcomponent,并将数据分配给另一个变量,但得到一个未定义的值i接收组件**
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)
}预先感谢
发布于 2022-04-21 03:01:33
我不建议订阅服务,让服务返回observable。此外,根据您的方法,您可以使用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
}https://stackoverflow.com/questions/71948279
复制相似问题