在角度2中使用async/await函数

Cam*_*ert 2 asynchronous async-await typescript angular

我试图找出如何在我的角度类中使用async/await.我有一个PostService从api获取帖子,但依赖于AreaService,以便PostService知道从哪个区域获取帖子.无法弄清楚如何告诉我的角度类PostService等待来自我的AreaService的数据.AreaService的正确响应是字符串"fun".然后PostService将在this.areas数组中使用这个有趣的字符串来显示当前所选区域中用户的帖子当前错误是:未捕获(在承诺中):错误:错误:0:0引起:无法读取属性'名字'未定义

postservice

    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());

        }
      }
Run Code Online (Sandbox Code Playgroud)

areaservice

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

area.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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

来自/ areas /的传入json

    [
        {
            "name": "fun"
        },
        {
            "name": "information"
        }
    ]
Run Code Online (Sandbox Code Playgroud)

Max*_*kyi 5

async/await如果您正在使用可观察对象,则不需要.您需要使用mergeMap运算符for rxjs@5flatMapfor rxjs@4:

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());
    });
}
Run Code Online (Sandbox Code Playgroud)