angular - 在 Angular 2 中使用异步/等待功能

标签 angular typescript asynchronous async-await

我想弄清楚如何在我的 Angular 类中使用 async/await。 我有一个从 api 获取帖子的 PostService,但它依赖于 AreaService,以便 PostService 知道从哪个区域获取帖子。无法完全弄清楚如何告诉我的 Angular 类 PostService 等待来 self 的 AreaService 的数据。 AreaService 的正确响应是字符串“fun”。 PostService 然后会在 this.areas 数组中使用这个有趣的字符串来向用户显示来自当前所选区域的帖子 当前错误是:Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'name' of undefined

邮政服务

    import { Injectable, OnDestroy } from '@angular/core';
        import { Http, Headers, RequestOptions, Response } from '@angular/http';
        import { Observable} from 'rxjs';
        import 'rxjs/add/operator/map';

        import { AuthenticationService, AreaService, MessageService} from './index';
        import { Post, Area} from '../_models/index';

        @Injectable()
        export  class PostService {
          areas: Area[] = [];
            constructor(
                private http: Http,
                private authenticationService: AuthenticationService,
                private areaService: AreaService,
                private messageService: MessageService
              ) {

            }

            getPosts(): Observable<Post[]> {
              this.areaService.getAreas().subscribe(area => { this.areas = area;});

            // add authorization header with jwt token
            let headers = new Headers();
            headers.append('Authorization','token ' + this.authenticationService.token);

            headers.append('Content-Type', 'application/json');
          let options = new RequestOptions({

          headers: headers
        });

            // get posts from api
            return this.http.get('http://localhost:8000/areas/'+ this.areas[0].name +'/', options)
                .map((response: Response) => response.json());

        }
      }

区域服务

    import { Injectable } from '@angular/core';
    import { Http, Headers, RequestOptions, Response } from '@angular/http';
    import { Observable, Subject } from 'rxjs';
    import 'rxjs/add/operator/map';

    import { AuthenticationService, MessageService } from './index';
    import { Area } from '../_models/index';

    @Injectable()
    export class AreaService {
      public areas: Observable<Area[]> ;
      subject:Subject<Area[]> = new Subject();
      public currentArea: string = "fun";
        constructor(
            private http: Http,
            private authenticationService: AuthenticationService,
          private messageService: MessageService) {
        }

       getAreas(): Observable<Area[]> {

            // add authorization header with jwt token
            let headers = new Headers();
            headers.append('Authorization','token ' + this.authenticationService.token);

            headers.append('Content-Type', 'application/json');
          let options = new RequestOptions({
          headers: headers
          });
            // get areas from api
            return this.http.get('http://localhost:8000/areas/', options)
                .map((response: Response) => response.json());

              //    this.areas = response.json();
            //      console.log("h");
            //      this.messageService.sendMessage(this.areas[0].name);


    //this.messageService.sendMessage(this.areas[0].name);
        }
    }

区域.ts

    import { Injectable } from '@angular/core';
    @Injectable()
    export class Area{
       name:string;
       currentArea:number = 1;

        constructor(name:string) {
            this.name = name;
        }

        public static createEmptyrea():Area{
            return new Area("");
        }
        setArea(val:number) {
            this.currentArea = val;
        }

    }

来自/areas/的传入 json

    [
        {
            "name": "fun"
        },
        {
            "name": "information"
        }
    ]

最佳答案

如果您使用的是可观察对象,则不需要async/await。您需要为 rxjs@5 使用 mergeMap 运算符或为 rxjs@4 使用 flatMap :

getPosts(): Observable<Post[]> {
    // subscribe until the area is available
    return this.areaService.getAreas().mergeMap(area => {

        // add authorization header with jwt token
        let headers = new Headers();
        headers.append('Authorization', 'token ' + this.authenticationService.token);

        headers.append('Content-Type', 'application/json');
        let options = new RequestOptions({

            headers: headers
        });

        // use the area to get the response
        return this.http.get('http://localhost:8000/areas/' + area.name + '/', options)
            .map((response: Response) => response.json());
    });
}

关于angular - 在 Angular 2 中使用异步/等待功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862073/

相关文章:

Angular:如何以法语格式显示日期

angular - 使用 Jest 时无法理解的单元测试效果错误

javascript - 当 Assets 发生变化时更新 service worker

reactjs - 如何让多个 child 设置一个父状态而不互相覆盖react js

javascript - Angular 4 与 AngularJs 指令

javascript - 使用Javascript如何解决异步问题?

multithreading - hibernate session 线程

html - 检查 tr 是偶数行还是奇数行以切换条纹表中的背景颜色

javascript - 从接口(interface)的键分配类型

swift - 如何在swift的后台进程子函数中将值返回给函数