如何在Angular 8中进行插值?

How to do interpolation in Angular 8?

我的 Angular 项目中有 2 个组件。组件A这样发送一个id:

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

现在将显示组件B并获取id。正如您在组件 B 的 ts class 中看到的那样,id 被保存到局部变量 id 中。当我将 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"...

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

这实际上与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);
    });

我想你只需要把这个 ('') 改成这个 (``)

因为 (') 表现得像一个普通字符串,而 (`) 表现得像某种 "smart" 字符串,它被称为模板文字

this.httpClient.get(`http://localhost:8080/p/api/v1/phonenumbers/getN/${id}`)

当使用 (') 时,您需要使用 +

将其连接在一起
this.httpClient.get('http://localhost:8080/p/api/v1/phonenumbers/getN/' + id)