behaviorsubject 获取元素
behaviorsubject get element
我有这样的结构
0:{id_schedule: 1}
1:{group_id: 1, last_name: "ame", name: "name", surname: "name"}
...
这是我的服务:
public lessonInfoList : BehaviorSubject<any> = new BehaviorSubject<any>(null);
getLessonInfo(model:any): Observable<any>{
return this.http.post("http://127.0.0.1:5000/lessoninfo",JSON.stringify(model))
.map((response:Response)=>{
this.lessonInfoList.next(response.json());
return response.json();
});
}
而且我需要将第一个元素 - "id_schedule" 存储在变量中,该怎么做?
我的组件:
constructor(private http:RequestService,private router: Router) {
this.http.lessonInfoList.subscribe(result => {
this.lessonInfoList = result;
我以为我可以这样做,但我错了:
this.id_schedule = result[0].id_schedule;
在你的情况下一切都是正确的,但是......
它是 Behavior 主题,所以你的第一个值将是 null,接下来是你想要得到的。
您必须像这样添加一个 if 检查:
constructor(private http:RequestService,private router: Router) {
this.http.lessonInfoList.subscribe(result => {
if(result) {
this.lessonInfoList = result;
this.id_schedule = result[0].id_schedule;
}
我有这样的结构
0:{id_schedule: 1}
1:{group_id: 1, last_name: "ame", name: "name", surname: "name"}
...
这是我的服务:
public lessonInfoList : BehaviorSubject<any> = new BehaviorSubject<any>(null);
getLessonInfo(model:any): Observable<any>{
return this.http.post("http://127.0.0.1:5000/lessoninfo",JSON.stringify(model))
.map((response:Response)=>{
this.lessonInfoList.next(response.json());
return response.json();
});
}
而且我需要将第一个元素 - "id_schedule" 存储在变量中,该怎么做? 我的组件:
constructor(private http:RequestService,private router: Router) {
this.http.lessonInfoList.subscribe(result => {
this.lessonInfoList = result;
我以为我可以这样做,但我错了:
this.id_schedule = result[0].id_schedule;
在你的情况下一切都是正确的,但是...... 它是 Behavior 主题,所以你的第一个值将是 null,接下来是你想要得到的。
您必须像这样添加一个 if 检查:
constructor(private http:RequestService,private router: Router) {
this.http.lessonInfoList.subscribe(result => {
if(result) {
this.lessonInfoList = result;
this.id_schedule = result[0].id_schedule;
}