【问题标题】:share data between two components (angular)在两个组件之间共享数据(角度)
【发布时间】:2018-09-13 15:51:46
【问题描述】:

我有一个场景,用户单击一个按钮来调用 Web 服务并将数据传递给第二个组件。 我查看了一些示例,但它不起作用,如果有人指出出了什么问题,将不胜感激。

组件A:

callService(id: any) {
    this.xService.getInfo(id).subscribe({
    data => this.myData = data;
    this.xService.setData(data);
    });
}

组件B:

ngOnInit() {
 this.xService.getData().subscribe(data => {this.myData = data; });
}

display() {
 console.log('test -- ' + myData.id);
}

服务:

Injectable()
export class XService {

  myData: BehaviorSubject<MyData> = new BehaviorSubject<MyData>(undefined);
  constructor(private httpclient: HttpClient) {}

  getInfo(id: string) {
        const param = new HttpParams()
        .set('id', Id);
        return this.httpclient.get<MyData>('/getxService', {params: param}).map(data => data);
  }

  getData(): Observable<MyData> {
        return this.myData.asObservable(); // <-- undefined from compB
  }

  setData(myData: MyData) {
      console.log('myData: ' + myData.id); // <-- this prints data (from compA)
      this.myData.next(myData);
  }
}

display() 不是在打印 id,而是在 service 下的 setData 打印了实际的 id。 我在想问题可能是我不能为 getData 放置 ngOnInit,因为 componentA 尚未调用,所以 getData 将是空白的。我想在单击显示按钮时调用 getData 。如果我将 getData 放在 display 下,它仍然无法工作......

【问题讨论】:

  • 您是否有不想通过第二个组件中的 Input 传递数据的原因?
  • 是的,因为 templateUrl 绑定到不同的 html。 componentA 的 html 与 componentB 不同
  • 没关系。您可以将组件 B 放在组件 A 的模板中,例如:组件 A.html: 。您可以添加一个 ngIf,它只会在有数据时使组件 B 可见。除非您要路由到其他页面,否则只需再次获取信息即可。
  • 这里有一篇很好的文章来解释它:angular.io/guide/component-interaction
  • 好吧,首先你没有在我能看到的任何地方打电话给display()

标签: angular


【解决方案1】:

添加此更改将起作用:

Injectable()
export class XService {
    private data: any = {};
    myData$: BehaviorSubject<MyData> = new BehaviorSubject<MyData>(undefined);
    constructor(private httpclient: HttpClient) {}

    getInfo(id: string) {
       const param = new HttpParams().set('id', Id);
       return this.httpclient.get<MyData>('/getxService', {params: param}).map(data => data);     
    }

    getData(): any {
       return this.data;
    }

   setData(myData: MyData) {
     this.data = myData;
     this.myData$.next(myData);
   }
}

在你的 B 组件中:

ngOnInit() {
    this.xService.myData$.subscribe(data => {this.myData = data; });
    this.myData = this.xService.getData();
}

display() {
 console.log('test -- ' + myData.id);
}

希望对你有帮助。

【讨论】:

  • 感谢您的输入,但数据仍然以“未定义”的形式出现,我在 html
    {{ display() }}
    中使用 display() 作为输出>
  • 要为此 +1,因为我认为我的问题与在数据到达之前检查数据有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2017-10-11
  • 2020-09-24
  • 2020-12-15
相关资源
最近更新 更多