Angular2 Observable,订阅和映射。通讯

时间:2017-01-24 10:25:45

标签: javascript angular typescript

我对Observables有疑问。我没有基本沟通的麻烦,例如: 服务:

getTableRecords(): Observable<RecordModel[]> {
        return this.http
            .get( this.API + 'records' )
            .map( (tableRecords: Response) =>  tableRecords.json().data as RecordModel[] )
            .catch(this.handleError);

    }

组件:

getTableRecords() {
        this.recordService.getTableRecords()
            .subscribe( tableRecords => { this.tableRecords = tableRecords; }, (err) => { this.error = err; console.log(this.error)})
    }

顶部示例运行良好,但我有一个额外步骤的问题。在我显示结果之前,我想根据参数与两个服务之间的通信过滤一个值:

服务I:

getTableRecords(): Observable<RecordModel[]> {
        return this.http
            .get( this.API + 'records' )
            .map( (res: Response) =>  res.json().data as RecordModel[] )
            .catch(this.handleError);

    }

服务II

getRecordDetail(assetId: string) {
        return this.rootService.getTableRecords()
            .map( (tableRecords:RecordModel[]) => {
                console.log("GET RECORDS TO ANOTHER SERVICE: ", tableRecords, assetId);
                (tableRecords:RecordModel[]) => tableRecords.filter( (tableRecord:RecordModel) => tableRecord.assetId === assetId )
            })
    }

组件:

tableRecord: RecordModel;

getRecordDetail() {
        this.sub = this.activatedRoute.params.subscribe(
            params => {
                if (params[ 'assetId' ] != undefined) {
                    let assetId:string = params[ 'assetId' ]
                   this.complianceDetailService.getRecordDetail(assetId)
                        .subscribe( result => this.tableRecord = result )
                } else console.log("UNDEFINED ASSETID");
            }
        );
    }

在COMPONENT中我在.subscribe( result => this.tableRecord = result )中遇到问题IDE大吼大叫说void无法分配给RecordModel类型。

请解释我可以制作这个序列: 第一:从一个服务获取数据, 二:在第二次服务中处理数据, 三:将数据返回到组件。

我想用Observables制作所有这些,因为我能用Promises做出相同的序列。

最诚挚的问候 Uland!

1 个答案:

答案 0 :(得分:1)

getRecordDetail(assetId: string) {
        return this.rootService.getTableRecords()
            .map( (tableRecords:RecordModel[]) => {
                console.log("GET RECORDS TO ANOTHER SERVICE: ", tableRecords, assetId);
                return  tableRecords.filter( (tableRecord:RecordModel) => tableRecord.assetId === assetId )
            })
    }