ngOninit() 上的异步/等待

kla*_*arn 5 asynchronous http angular

我正在尝试使用async/ await(第一次),但我无法理解它。

我在这里做错了什么:

tree.component.ts

export class TreeComponent implements OnInit {

  private routeSub: any;
  acronym: string;
  flare: any[];

  constructor(
    private location: Location,
        private route: ActivatedRoute,
        private http: HttpClient,
        private router: Router,
        private fileTreeService: FileTreeService
  ) {


  }
  ngOnInit(): void {
      this.routeSub = this.route.params.subscribe(
        params => {
            this.acronym = params.name
            this.fileTreeService.getFileTree(params.name).subscribe(item => {
                this.flare = item;

            });
        });
Run Code Online (Sandbox Code Playgroud)

文件树.service.ts

export class FileTreeService {

    res: any;

    constructor(private http: HttpClient) { }



    async getFileTree(acronym) {
        const headers = new HttpHeaders()
        this.res = await this.http.get<any>(`${IP}/filetree/tree/`, { headers });
        return this.res;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在 filetree.component.ts 中收到错误“‘Promise’类型上不存在属性‘subscribe’”。我已经走到了路的尽头,所以我正在向你们伸出援手。提前致谢。

更新:

感谢您的帮助,它有点工作,但没有达到我想要实现的目标。是不是应该先等待结果再继续执行代码?

  ngOnInit(): void {
      this.routeSub = this.route.params.subscribe(async (params) => {
            this.acronym = params.name
            this.flare = await this.fileTreeService.getFileTree(params.name).toPromise();
            console.log("flare = ", this.flare);
        });

    let test = this.flare;
    console.log("test = ", test);
} 

Run Code Online (Sandbox Code Playgroud)

root 在为flare 赋值之前声明。这是我的浏览器控制台输出的内容。

test =  undefined
flare =  {name: "data", children: Array(81)}
Run Code Online (Sandbox Code Playgroud)

mal*_*awi 6

async/await 在 Promise 上工作,因此如果您使用 httpClinet 方法,您需要通过toPromise方法将 Observable 的返回值转换为 Promise

文件树.service.ts

export class FileTreeService {
    res: any;

    constructor(private http: HttpClient) { }

    getFileTree(acronym) {
        const headers = new HttpHeaders()
        // return an observable 
        return  this.http.get<any>(`${IP}/filetree/tree/`, { headers })    
   }
}
Run Code Online (Sandbox Code Playgroud)

成分

  ngOnInit(): void {
      //  mark the upper function with async
      this.routeSub = this.route.params.subscribe(async (params) => {  
        this.acronym = params.name;
        //  now we can use await but we need to convert the observable to promise 
        this.flare = await this.fileTreeService.getFileTree(params.name).toPromise();
        });
}
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读深入教程

更新

我们可以将 ngOnInit 标记为 async,并在将 theme 转换为 Promise 后使用 wait 来执行所有操作,在这种情况下,我们将不再使用 subscribe。

  //  mark the upper function with async
  async ngOnInit(): Promise<void> {
    //  now we can use await but we need to convert the observable to promise 
    this.acronym = (await this.route.params.toPromise()).name;
    this.flare = await this.fileTreeService.getFileTree(this.acronym).toPromise();
    let test = this.flare;  // => {name: "data", children: Array(81)}
    console.log("test = ", test); // => {name: "data", children: Array(81)}

  }
Run Code Online (Sandbox Code Playgroud)