Search code examples
angularnativescript

NativeScript with Angula pass parameter to url


I am trying to pass a parameter to the URL and display the information base on the parameter that was passed to the URL. I have a list of provinces, what I trying to do is when a user clicks on a particular province I want to take that province and pass it to the URL and display that district that belongs to the province that was clicked. I am not sure what I did wrong, when I press a province nothing happens and it doesn't load.

example URL: https://example.com/province/?province_name=aprovince

services.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> 

Solution

  • You need to use HttpParams from angular. And pass it in your http get call. Your code will look like this.

    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});
    }
    

    NOTE: you don't need to pass / at the end of url while using query params.