【问题标题】:Passing Data between directive/component via service通过服务在指令/组件之间传递数据
【发布时间】:2018-10-03 16:45:08
【问题描述】:

我正在尝试通过服务将数据从指令传递到组件。 我的传输服务文件返回的结果是类型“传输”不能分配给观察者。尝试订阅服务时,我的组件文件中的类型 '() => Observable' 上不存在属性 'subscribe'。为什么会这样,我该如何解决? 我的文件是

transfer.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Transfer } from './transfer';

@Injectable()
export class TransferService {

  constructor(private transfer: Transfer){}

  private pageData;
  private contentData;
  private contentBox;

  setData(pData, cData, bData){
    this.pageData = pData;
    this.contentData = cData;
    this.contentBox = bData;
  }

  getData(): Observable<Transfer>{
    this.transfer.page = this.pageData;
    this.transfer.content = this.contentData;
    this.transfer.contentBox = this.contentBox;
    this.clearData();
    return this.transfer;
  }

  clearData(){
    this.pageData = undefined;
    this.contentData = undefined;
    this.contentBox = undefined;
  }
}

transfer.ts

import { ElementRef } from '@angular/core';
export interface Transfer{
    page: [
        {
            pageNum: number,
            subStart: number,
            subEnd: number
        }   
    ];
    content: string;
    contentBox: ElementRef;
}

article.component.ts - 组件

  transfer(){
    this.ts.getData.subscribe(data => this.tsData = data);
  }

paginator.ts - 指令

// Pass date via transferservice.ts
transfer(){
  this.ts.setData(this.pageJump, this.content, this.contentBox);
}

编辑: 使用@ritaj 的解决方案解决了不可分配/属性不存在的问题,但现在我收到“错误:无法解析 TransferService 的所有参数

堆栈闪电编辑: https://stackblitz.com/edit/mesh

【问题讨论】:

  • 你的组件构造函数中传递TransferService了吗?
  • 您不需要服务方法来返回它的一个属性。您可以使用this.ts.transfer.subscribe() 直接从组件中访问它(假设服务已注入其中并且transfer 是公共的)。
  • @berensn ,你能在 Stackblitz 上展示它吗?
  • @JeremyThille 我尝试了您的解决方案,但 'subscribe() 不是传输类型的属性',所以我会将它添加到我的 transfer.ts 文件中的某个地方以使其正常工作吗?

标签: angular service components directive subscribe


【解决方案1】:

您的 getData() 服务方法不会返回 Observable,因为您有 typed。

它只是返回一个普通的 JS 对象,显然没有 .subscribe() 方法。

将您的 article.component.ts transfer() 方法更改为:

transfer(){
    this.tsData = this.ts.getData();
  }

并将 getData 签名更改为:

getData(): Transfer {}

【讨论】:

    【解决方案2】:

    article.component.ts

      constructor(public ts : TransferService){}
      transfer(){
         this.tsData = this.ts.getData();   // directly call
      }
    

    在 app.module.ts 中注入服务:-

    providers:[TransferService]
    

    这里是 Stackblitz 链接,只是一个反映问题解决方案的演示:-

    https://stackblitz.com/edit/angular5-service-example-onwtg6?file=app/article.component.ts

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 2018-12-31
      • 2019-06-04
      • 2015-06-28
      • 2020-07-23
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多