我是角度2和RXJS Observables的新手,我从早上起做了一件事,它完成但是我无法弄清楚它是如何工作的。
这是Assests/api
文件夹下的test.json文件:
[ {
"name" :"James T",
"address": {
"Street" : {
"data": ["Austin","I","J"]
},
"District":"XYZ",
"test" : {
"insideTest":"insideTest1"
}
}
},
{
"name" :"James T 2",
"address": {
"Street" : {
"data": ["Austin2","I2","J2"]
},
"District":"XYZ 2",
"test" : {
"insideTest":"insideTest2"
}
}
},
{
"name" :"James T 3",
"address": {
"Street" : {
"data": ["Austin3","I3","J3"]
},
"District":"XYZ 3",
"test" : {
"insideTest":"insideTest3"
}
}
}
]
然后我有一个服务公开这个名为questionService.ts
的api,这是代码:
getTheJsonFile(): Observable<any[]>{
return this._http.get('assets/api/test.json')
.map(response=>{
return response.json();
});
}
最后在我的组件中,我将此服务称为:
import { Component, OnInit } from '@angular/core';
import {Campaign} from '../models/campaign';
import {Questions} from '../models/questions';
import {QuestionService} from '../question/question.service';
import { Http , Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import "rxjs/add/operator/mergeMap";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-campaign',
templateUrl: './campaign.component.html',
styleUrls: ['../custom.css'],
providers: [QuestionService]
})
export class CampaignComponent implements OnInit {
questionTypes: any;
questions: Questions[];
public campaign: Campaign;
constructor(public questionService : QuestionService,private _http: Http) {
}
ngOnInit() {
this.getTheJson()
.subscribe(data => {
console.log("And the data is--->"+data["address"]["Street"]["data"]);
data["address"]["Street"]["data"].forEach(test=>console.log("Test Data-->"+test))
});
}
getTheJson(): Observable<any>{
return this.questionService.getTheJsonFile()
//.map(element => element)
//.do(x => console.log("Mydata--->"+JSON.stringify(x)))
.flatMap(element => element)
}
}
现在我的问题是,如果我从getTheJson()方法中删除flatMap(element => element)
,它将返回null / undefined,为什么会发生这种情况?
再次如果我调用map()而不是flatMap(),那么它也会返回未定义的结果。
虽然在另一方面我有另一种方法完全相同,但为此我不需要调用flatMap()。请帮忙!
答案 0 :(得分:1)
你解码的json是一个对象数组。 flatMap
基本上会将其转换为一次发出一个对象的observable:
object...object...object...
删除flatMap
后,您从订阅中获得的内容只会变成一个值:
[object, object, object]
所以你必须相应地调整,因为这段代码失败了:
subscribe(data => {
// data["address"] is undefined because you're getting an array of objects
data["address"]["Street"]["data"].forEach(test=>console.log("Test Data-->"+test))
})
因此,在删除flapMap
后,您可以执行以下操作:
subscribe(data => {
data.forEach(person => {
console.log(`name: ${person.name}`,`street: ${person.address.street.data}`);
});
})