在Angular 7中将可观察的数据转换为数字或字符串

时间:2019-03-11 06:32:50

标签: angular

这个问题可能已经回答了,但是我仍然找不到解决问题的方法: Angular-convert-a-observablenumber-to-a-numberhow-to-convert-observable-data-to-a-number-in-angular6

我正在尝试使用length,next和prev变量。这些变量定义为:

let length = this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['count']));
let next = this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['next']));
let prev = this.http.get<Project[]>(this.projectUrl).pipe(map(res=> res['previous']));

我必须将这些变量 typecast 转换为数字,这将使我能够编写自定义分页功能。我尝试使用 <> 关键字对它们进行类型转换,如下所示(尽管这不是明智的方法):

private length0 = <unknown> this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['count']));
public length1 = <number> this.length0;

private next0 = <unknown> this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['next']));
public next1 = <string> this.next0;

private prev0 = <unknown> this.http.get<Project[]>(this.projectUrl).pipe(map(res=> res['previous']));
public prev1 = <string> this.prev0;

但是当我检查控制台时,它们仍然是 Observable()类型。

有人可以建议我如何将这些变量转换为数字吗?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用async / await来将可观察对象转换为Promise

let length = await this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['count']))toPromise();
  

您需要添加异步才能使用await

async ngOnInit() {
  let length = await this.http.get<Project[]>(this.projectUrl).pipe(map(res => res['count']))toPromise();
}

stackblitz demo