首页 > 解决方案 > 带有 Angular 的 NativeScript 将参数传递给 url

问题描述

我正在尝试将参数传递给 URL,并根据传递给 URL 的参数显示信息。我有一个省份列表,我想要做的是当用户点击一个特定省份时,我想将该省份传递给 URL 并显示属于被点击省份的那个地区。我不确定我做错了什么,当我按下一个省份时,什么也没有发生,也没有加载。

示例网址:https ://example.com/province/?province_name=aprovince

服务.ts

export class DistrictService {
    districtArray: Array<ProvinceData> = [];
    url = "https://example.com/province";
    headers = new HttpHeaders({
        "Content-Type": "application/json",
        Authorization: "Token 5a72afc446dd4c38e5f99"
    });

    constructor(private http: HttpClient) { }

    getInfo(): any {
        return this.http.get(this.url, {headers: this.headers});
    } 

    getProvince(province: string){
        return this.http.get<ProvinceData>(`${this.url}${province}/`, {headers: this.headers});
      }

}
@Component({
  selector: "ns-district",
  templateUrl: "./district.component.html",
  styleUrls: ["./district.component.css"],
  moduleId: module.id
})
export class DistrictComponent implements OnInit {
    districtData: ProvinceData;
   
    // tslint:disable-next-line: max-line-length
    constructor(private districtservices: DistrictService, private route: ActivatedRoute, private router: RouterExtensions) { }

    ngOnInit(): void {
        const province = this.route.snapshot.params.province;
        this.districtservices.getProvince(province).subscribe(
            (data: ProvinceData) => {
            this.districtData = data;
            console.log(province)
            },
            (error) => console.error(error)
            )
        }            
    }
<StackLayout  *ngIf="districtData">         
    <GridLayout android:useDefaultMargins="true" class="test" columns="auto,100" rows="auto,auto" width="2000" height="30" *ngFor="let item of districtData.district">            
        <Label class="list-province" nsRouterLink ="/district" [text]="item" col="0" row="0"></Label>
        <Label class ="arrow-icon" text="&#xf0a9;" class="fas" col="1" row="0" ></Label>
    </GridLayout>
</StackLayout> 

标签: angularnativescript

解决方案


您需要HttpParams从角度使用。http get并在你的电话中传递它。您的代码将如下所示。

let httpParams = new HttpParams();
httpParams = httpParams.append(province_name, value);

getProvince(province: string){
        return this.http.get<ProvinceData>(`${this.url}${province}`, {headers: this.headers, httpParams});
}

注意:使用查询参数时,您不需要/在 url 末尾传递。


推荐阅读