首页 > 解决方案 > 如何在 Angular 8 中进行插值?

问题描述

我的 Angular 项目中有 2 个组件。组件 A 以这种方式发送一个 id:

<a [routerLink]="['/numbersbyareacode', element.id]">
   {{element.title}} 
</a> 

现在将显示组件 B 并获取 id。id 保存到局部变量 id 中,如您在组件 B 的 ts 类中所见。当我将 id 打印到控制台时,它将显示给定的 id。

B组份:

id: any;

constructor(private route: ActivatedRoute, private httpClient: HttpClient) {
}

ngOnInit() {
  this.id = this.route.snapshot.paramMap.get('id');
  console.log(this.id);
  this.getAllNumbersByAreacode();
  this.dataSource.paginator = this.paginator;
}

getAllNumbersByAreacode() {
    // tslint:disable-next-line: max-line-length
    this.httpClient.get('http://localhost:8080/p/api/v1/phonenumbers/
    getN/${id}').subscribe((res: any[]) => {         //this interpolation doesn't work
      console.log(res);
    });
}

我正在尝试将 id 添加到路径中,但我做错了,因为在控制台中显示的路径出现错误,如下所示:

"http://localhost:8080/p/api/v1/phonenumbers/getN/$%7Bid%7D"...

谁能告诉我我做错了什么?

标签: angulartypescriptinterpolation

解决方案


这实际上与 Angular 没有任何关系,它只是关于 javascript。模板文字是使用反引号编写的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

所以你应该使用反引号(`)而不是单引号(')

this.httpClient.get(`http://localhost:8080/p/api/v1/phonenumbers/getN/${id}`)
    .subscribe((res: any[]) => {
      console.log(res);
    });

推荐阅读