【问题标题】:behaviorsubject get element行为主体获取元素
【发布时间】:2018-03-05 17:04:31
【问题描述】:

我有这样的结构

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;

【问题讨论】:

  • 这与behaviourSubjects 无关......事实上,您的问题中没有任何内容表明它是一个行为主题。鉴于我所看到的,这是一个可观察的。现在你的问题是什么?请阅读this
  • @MikeTung 现在看起来像 behaviorSubjects?

标签: angular behaviorsubject


【解决方案1】:

在你的情况下,一切都是正确的,但是...... 它是 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;
     }

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2016-09-19
    • 2018-11-20
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多