首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从angular13中的服务中获取未定义的值

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

Stack Overflow用户
提问于 2022-04-21 02:37:13
回答 1查看 526关注 0票数 1

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

sending.component.ts

代码语言:javascript
复制
import{sharedservice}....
constructor(private services:sharedservice)
ngOnInit(){
this.formvalue()
}
this.formvalue(){
this.services.getdata(this.form.value)
}

shared.services.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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)
}

预先感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-21 03:01:33

我不建议订阅服务,让服务返回observable。此外,根据您的方法,您可以使用subject或类似的方法来通知您的receiving组件。

代码语言:javascript
复制
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();
   }
}

发送组件

代码语言:javascript
复制
constructor(private services:sharedservice) {}

ngOnInit() {
   this.formvalue()
}

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

接收组件

代码语言:javascript
复制
...
 constructor(private services:sharedservice) {}
   
  ngOnInit() {
    this.services.getDataOfService(data)
     .subscribe((response) => console.log(response)) // and here as well
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71948279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档