简体   繁体   English

角度:将参数传递给this.http.get()

[英]Angular: pass Parameter to this.http.get()

I have an angular APP that need dynamically get the data from API. 我有一个有角度的APP,需要从API动态获取数据。 when I use static URL its work properly. 当我使用静态网址时,它可以正常工作。

here my code 这是我的代码

service.ts

export interface MachineData {
  name: string;
  status: string;
}

@Injectable()
export class MachineService {
  BASE_URL = 'example.com/api/v1/id/1';

  constructor(private http: HttpClient) { }

  getMachineData() {
    return this.http.get(this.BASE_URL);
  }
}

component.ts

showMachine() {
    this.machineService.getMachineData()
    .subscribe((data: machineData) => this.machineData = {
        status: data['status'],
    });
}

markers: marker[] = [
    {
        id: 1,
        name: "Marker A",
        lat: -6.949065,
        lng: 107.592339,
    },
    {
        id: 2,
        name: "Marker B",
        lat: -6.935582,
        lng: 107.610037,
    }
]

component.html

<agm-marker
    *ngFor="let m of markers; let i = index"
    (markerClick)="showMachine(m.id, i)"
    [latitude]="m.lat"
    [longitude]="m.lng"
    [label]="m.name">

    <agm-info-window>
        <strong>
            <p>Status : {{machineData.status}}</p>
        </strong>
    </agm-info-window>
</agm-marker>

how to make the URL dynamic?... I mean add the ID to the URL. 如何使URL动态?...我的意思是将ID添加到URL。

example: 例:

from this 由此

return this.http.get(this.BASE_URL);

to this 对此

return this.http.get(this.BASE_URL + id);

so I can retrieve data by id. 这样我就可以按ID检索数据。 already trying by do like this : 已经尝试这样做:

on my component.html 在我的component.html

(markerClick)="showMachine(m.id)"

on my component.ts 在我的component.ts

showMachine(id: number) {
    this.machineService.getMachineData(id: number)
    .subscribe((data: machineData) => this.machineData = {
        status: data['status'],
    });
}

and my service.ts 和我的service.ts

return this.http.get(this.BASE_URL + id);

but it's not work. 但这是行不通的。

id is a number, URL a string. id是数字,URL是字符串。

Thus, you want to convert the id to string first before doing "url + id". 因此,您要先将id转换为字符串,然后再执行“ url + id”。

ie something like this does work. 即这样的事情确实起作用。 Without the "toString" you will get "NaN" in the concatenation. 如果没有“ toString”,则串联中将得到“ NaN”。

let url: string;
let id: number;

id = 5
url = "http://something/";

let result = url + id.toString();

console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM