【问题标题】:Trying to pass the data between the component using the service尝试使用服务在组件之间传递数据
【发布时间】:2020-01-27 09:11:04
【问题描述】:

我正在使用服务在组件之间传递数据,我的组件如下所示

  constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) {

  }
  ngOnInit() {
    this.psService.getTDate().subscribe(x => this.cachedResults = x);
    this.populateArrays();

我的服务在哪里

 constructor(private service: DataService, private pInfo: ProjectDetailsComponent) {

    this.rProjectNumber = this.pInfo.rProjectNumber;
    this.rProjectSO = this.pInfo.rSalesOrder;
    this.entityUrl = this.pInfo.entityUrl;
    this.tDate = service.get<ShipDateFilterModel[]>(this.entityUrl);
   }

即使 tDate 有数据,在 Component 中订阅它时也没有数据。当在 ngOnInIt 生命周期钩子上调用服务时,this.cachedResults 为空。我在这里错过了什么?

【问题讨论】:

  • 可能是因为它甚至在您订阅之前就有数据并且在您订阅之后没有发出。
  • @Manish 我如何发出它。
  • 在下面查看我的答案,这将解决您的问题..

标签: javascript angular typescript angular7


【解决方案1】:

试试这个方法..

export class ProjectShipmentService {
  rProjectNumber;
  tDate: Observable<ShipDateFilterModel[]>;
  entityUrl;
  rProjectSO;

  constructor(private service: DataService, private pInfo: ProjectDetailsComponent) {
    this.rProjectNumber = this.pInfo.rProjectNumber;
    this.rProjectSO = this.pInfo.rSalesOrder;
    this.entityUrl = this.pInfo.entityUrl;
   }

getTDate(){
    return this.service.get<ShipDateFilterModel[]>(this.entityUrl);
}

在你的组件中。

  ngOnInit() {
    this.psService.getTDate.subscribe(x => this.cachedResults = x);
    this.populateArrays();
  }

希望这会有所帮助:)

【讨论】:

  • 我收到了类似Property 'subscribe' does not exist on type '() =&gt; Observable&lt;ShipDateFilterModel[]&gt;'.ts(2339) 附上截图的错误
  • 你的方法service.get它返回什么?
  • 来自 API 的响应
  • 你能分享那个方法的代码吗?它应该返回一个 observable。
  • 检查一下,我已经使用公共 api 创建了演示,现在它工作正常,您可以比较并查看有什么区别,并且可能是正确的。 stackblitz.com/edit/angular-kttgph
【解决方案2】:

你为什么不简单地在服务中创建一个方法,比如

getTDate(){
return this.service.get<ShipDateFilterModel[]>(this.entityUrl);
}

然后订阅你的组件

this.psService.getTDate().subscribe(x => this.cachedResults = x);

【讨论】:

  • 我收到类似“()类型上不存在属性“订阅”的错误 => Observable'.ts(2339) 附上截图
  • @trx 你能在你的问题中显示service.get 功能代码吗
  • @trx 你能检查一下你的代码看起来像this.psService.getTDate(),subscribethis.psService.getTDate.subscribe 它应该是this.psService.getTDate(),subscribe 根据我的回答可能是你犯了与此SO stackoverflow.com/q/44092034/5621827 中指定的相同的错误
  • 错误已解决,但我在this.cachedResults中仍然看不到任何数据
  • @trx 你能把console.log 加入subscribe(x =&gt; {console.log(x)}) 之类的订阅方法中,看看是否被触发并记录到控制台
猜你喜欢
  • 2019-03-20
  • 2020-07-23
  • 2018-10-03
  • 2021-04-25
  • 1970-01-01
  • 2017-08-23
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多