如何使用RxJS设置地图中未包含的值?

如何使用RxJS设置地图中未包含的值?

问题描述:

我刚刚开始使用Angular 4,并且有一个我一直在研究的项目,涉及显示使用REST API检索的数据。数据似乎正在被正确检索并且表单正确填充。如何使用RxJS设置地图中未包含的值?

现在,从API返回的其中一个值只包含一个字符。我希望覆盖setter方法来将单个字符扩展为完整的字符串。我知道我可以改变这个调用来返回完整的字符串,但是API是由多个前端支持的,我希望能够保持它们的一致性。这plunker要什么,我希望做(不REST API参与):Plunker example

当在我的项目的订阅功能记录,fullStatus不包括:

this.service.get(id).subscribe(p => { 
    this.test = p; 
    console.log(this.test); 
}); 

在这里添加switch语句,事情按预期工作,但我希望将这个逻辑绑定到Test类中,而不是订阅功能。

this.service.get(id).subscribe(p => { 
    this.test = p; 
    switch (this.test.status) { 
     case 'A': 
     this.test.fullStatus = 'Active'; 
     break; 
     case 'I': 
     this.test.fullStatus = 'Inactive'; 
     break; 
     case 'N': 
     this.test.fullStatus = 'No Certificate'; 
     break; 
     default: 
     this.test.fullStatus = ''; 
     break; 
    } 
    console.log(this.test); 
    }); 

有没有更好的方法来处理这个问题?提前致谢。

不能你做你的结果的map包括这fullStatus属性?

在服务,

// assuming you have to convert the response to json 
get(id) { 
return this.http.get(<url-to-get>).map((res) => { 
    let test = res.json(); 
    switch (this.test.status) { 
     case 'A': 
     test['fullStatus'] = 'Active'; 
     break; 
     case 'I': 
     test['fullStatus'] = 'Inactive'; 
     break; 
     case 'N': 
     test['fullStatus'] = 'No Certificate'; 
     break; 
     default: 
     test['fullStatus'] = ''; 
     break; 
    } 

    return test; // returns each response element with the new property 'fullStatus' added based on its 'status' 
}); 
} 

然后,你可以简单地订阅它在你的组件类。希望能帮助到你。

+0

这是有道理的,它与我目前在我的组件类中订阅的内容类似。我只是希望能够在数据类中以某种方式存在逻辑。 – Tommo

您可以创建一个测试类像测试model.ts:

export class Test { 
     prop1 = ''; // dummy property (you can define these according to your need 
     prop2 = ''; 

     status: string; 
     fullStatus?: string; // optional 

     init(responseData: any){ 
     this.prop1 = responseData.prop1 ; 
     this.prop2 = responseData.prop2 ; 
     this.status = responseData.status; 
     switch (responseData.status) { 
       case 'A': 
        this.fullStatus = 'Active'; 
        break; 
       case 'I': 
        this.fullStatus = 'Inactive'; 
        break; 
       case 'N': 
       this.fullStatus = 'No Certificate'; 
        break; 
       default: 
       this.fullStatus = ''; 
       break; 
     } 
     } 
    } 

在组件:API调用后

import {Test} from './test-model'; 

    export class TestComponent implements OnInit 
    { 
     test: Test = new Test(); 
     constructor(private service: MyService){} 

     ngOnInit(){ 
     this.service.get(id).subscribe(p => { 
      this.test.init(p); 

      console.log(this.test); 
     }); 
     } 
    }