Angular 5订阅不会将数​​据分配给列表

时间:2018-04-22 11:38:01

标签: angular

我无法将数据分配给我的qMList。控制台始终显示该列表未定义。 Web服务正在运行,数据即将到来,因为可观察到的问题是数据未分配给qMList。

@Injectable()
export class QuestionService {

  public qMList: QuestionMaster[] ;

    constructor(private http: HttpClient) {

    }

    getOsz():Observable<QuestionMaster[]>{

      return this.http.get<QuestionMaster[]>("http://localhost:7073/api/values");

    }

    getQuestions() {

      this.getOsz().subscribe(res => this.qMList = res);

      console.log(this.qMList);

      }
}

1 个答案:

答案 0 :(得分:1)

问题是因为http请求是异步的,你应该等待它来满足

@Injectable()
export class QuestionService {

  public qMList: QuestionMaster[] ;

    constructor(private http: HttpClient) {

    }

    getOsz():Observable<QuestionMaster[]>{

      return this.http.get<QuestionMaster[]>("http://localhost:7073/api/values");

    }

    getQuestions() {

      this.getOsz().subscribe(res => {
            this.qMList = res;
            console.log(this.qMList);
      });

      }
}