Angular 8在订阅中等待REST API响应

时间:2019-11-20 14:04:24

标签: javascript angular typescript angular8

在component.ts中,我有调用api并使用响应的方法。我收到一个空数组,因为它没有在订阅中等待

disp(): String[] {
    let scores: String[] = [];
    this.assessmentService.getPrograms().subscribe(
      (res: AssessmentResponse[]) => {
        res.map(
          function (t) {
            const body = `{id: ${t.id}, name: "${t.name}"}`;
            scores.push(body);
          })
        return scores;
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occured.");
        } else {
          console.log("Server-side error occured.");
        }
      });
    console.log("returned");
    return scores;
  }

我想存储从disp返回的数组

 programList$ = observableOf(this.disp);

然后我使用programList $来设置选项的值,我发布了一小段代码,因为它具有多个选项卡

 tabs: TabType[] = [
    {
      label: 'Assign Program',
      fields: [
        {
          fieldGroupClassName: 'display-flex',
          fieldGroup: [
            {
              className: 'flex-1',
              key: 'campaign',
              type: 'select',
              templateOptions: {
                label: 'Campaign',
                placeholder: 'Select Campaign',
                // description: 'Campaign Name',
                required: true,
                options: this.programList$,

这是我的服务电话

 public  getPrograms(): Observable<AssessmentResponse[]> {

         return this.http.get(this.endpoint,this.headers.httpOptions)
         .pipe(map((data: EmbeddedAssessmentsResponse) => data._embedded.programs));          
    }

PS:我是棱角文字和打字稿的新手,我们将为您提供帮助。

2 个答案:

答案 0 :(得分:0)

如果您的programList$是一个Observable,则您的disp()方法应返回一个Observable: programList$ = this.disp();

disp(): Observable<String[]> {
  return this.assessmentService.getPrograms().pipe(
    map((res: AssessmentResponse[]) => {
        return res.map(t => `{id: ${t.id}, name: "${t.name}"}`);
      }),
    catchError((err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occured.");
        } else {
          console.log("Server-side error occured.");
        }
        return of([]);
      });
  );

答案 1 :(得分:0)

由于订阅回调是异步执行的,因此如果您在执行回调之前尝试读取它,则数组将为空。

只需在组件中创建属性programList,并在执行订阅回调时分配从API返回的数据,然后调用一个函数来创建tabs数组。您可以尝试这样的事情:

programList: string[];
tabs: TabType[];

disp(): void {
    this.assessmentService.getPrograms().subscribe(
      (res: AssessmentResponse[]) => {
        let scores: String[] = [];
        res.map(
          function (t) {
            const body = `{id: ${t.id}, name: "${t.name}"}`;
            scores.push(body);
          })
        this.programList = scores;
        this.createTabsArray();
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log("Client-side error occured.");
        } else {
          console.log("Server-side error occured.");
        }
      });
}

createTabsArray(): void {
    this.tabs = [
    {
      label: 'Assign Program',
      fields: [
        {
          fieldGroupClassName: 'display-flex',
          fieldGroup: [
            {
              className: 'flex-1',
              key: 'campaign',
              type: 'select',
              templateOptions: {
                label: 'Campaign',
                placeholder: 'Select Campaign',
                // description: 'Campaign Name',
                required: true,
                options: this.programList,
                ...
                ...
                }
            ...
            ...
            }]
}