angular 5将一个或多个变量传递给服务

时间:2018-02-21 16:48:12

标签: angular

您好,这可能非常容易但我已经挣扎了2天。 我想从[(ngmodel)]将变量传递给我的服务 天气组件中随处可见的字符串。 当我键入任何城市。 我尝试了所有我能想到但没有成功的东西, 那么我如何传递随着我输入的城市而改变的ngmodel 到服务网址。 我有这个获取功能的网址。 但无论我尝试什么,我都无法改变变化?如果我硬编码一个城市,onli的作品.. 像这样 我的服务ts

public globalVar='berlin';

   return this.http
             .get('http://api.openweathermap.org/data/2.5/weather?q='+'$globalVar'+'&APIkey=f0a4b73f313ac53530db02abf0781')
             .map((response: Response) => {
                 return <IPosts[]>response.json();
             })
             .catch(this.handleError);
     }

我尝试过多次,但无论我放入什么 角度拒绝使globalVar成为一个变量而且只是显示 $ globalVar + apikey = f0 ETZ 在consolelog中。

2 个答案:

答案 0 :(得分:3)

你需要

  .get('http://api.openweathermap.org/data/2.5/weather?q= `${globalVar}&APIkey=f0a4b73f313ac53530db02abf0250781`)

答案 1 :(得分:1)

在输入字段中使用<input type="text" [(ngModel)]="model" (ngModelChange)="setValue($event)"> @Component({...}) export class FooComponent { setValue(value: string) { this.myService.value = value; } } 事件来设置从模型到服务的值。

示例:

public myVariable = 'world';

// ...

`Hello ${myVariable}`

此外,您在服务URL中的ES6语法中输入了拼写错误。使用模板字符串如下:

{% for spending in category.spending_set.all %}

Template literals documentation