Ionic 通过点击标签进行Angular 搜索

z4iuyo4d  于 2023-02-10  发布在  Ionic
关注(0)|答案(1)|浏览(188)

在我的应用程序中,我试图使一个功能,当用户点击标签时,它会向他显示所有具有此标签的产品...
我的搜索请求是通过API调用使用GET方法发出的...因此,我试图实现的是,在单击标记时,标记值将作为url中的参数发送,从而在新页面中返回带有此标记的所有产品...我的API调用在POSTMAN中有效,但在Angular中实现时遇到了问题...
因此,我的主要问题是:
1.如何使标记可单击,以便它使用api请求发送值
1.如何将routerlink添加到标记中,以便它重定向到新页面,在该页面中显示带有此标记的所有产品
我是非常新的Angular ,所以请帮助:)
这是标签在应用程序中显示的图像:

下面是我的代码:home.page.html中用于输出标记的HTML:

<ion-chip *ngFor="let tag of tags">
    <ion-label>{{ tag.tags }}</ion-label>
  </ion-chip>
    • search.service.ts中搜索API的代码:**
searchByTagCall(tag: string) {
    return from(Preferences.get({key: 'TOKEN_KEY'})).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        let params = new HttpParams();
        params = params.append('tag', tag);
        return this.httpClient.get(`${environment.apiUrl}search`, {headers, observe: 'response', params});
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', {replaceUrl: true});
        }
        return EMPTY;
      }),
    );
  }
    • 主页ts代码:**
searchByTag() {
    this.searchService.searchByTagCall(tag).subscribe(
      (data: any) => {
        /* what do I put here? */
      },
      error => {
        console.log('Error', error);
      });
  }
    • 我的JSON如下所示:**
{
  "tags": [
    {
      "tags": "fruit"
    },
    {
      "tags": "sour"
    },
    {
      "tags": "sweet"
    },
    {
      "tags": "frozen"
    },
    {
      "tags": "fresh"
    },
    {
      "tags": "vegetable"
    },
    {
      "tags": "raw"
    }
  ]
}
qcuzuvrc

qcuzuvrc1#

执行以下更改:

主页.html:

<ion-chip *ngFor="let tag of tags">
    <ion-label class="tag" (click)="searchByTag(tag.tags)">{{ tag.tags }}</ion-label>
</ion-chip>

主页.scss:

// In case you need to change the cursor to be the hand icon
.tag {
    cursor: pointer; 
}

主页.ts

constructor(/*whatever parameters you have in your constructor already*/, private router: Router, private dataService: DataService) {
    // Whatever code you have in your constructor
}

searchByTag(tag: string) {
    this.searchService.searchByTagCall(tag).subscribe((data: any) => {
        // 1. Store the data in some service so it will be accessible for the other page
        this.dataService.tagData = data;

        // 2. Navigate to the other page (you can store the tag in the route params if you need it)
        this.router.navigate(['/tagPage/', tag]); 
    },
    error => {
        console.log('Error', error);
    });
}

相关问题