簡體   English   中英

如何將我的 ionic 應用程序連接到同一頁面中的兩個不同的 API URL? 如何將第一個 url 數據中的 id 傳遞給第二個 url?

[英]How can I connect my ionic app to two different API URLS in the same page? how to pass the id from the first url's data to the second url?

我正在構建一個離子食譜應用程序,主頁正在使用 API url 調用食譜名稱、ID 和圖像列表,即 www.forexample/recipeslist.Z4D236D9A2D102C5FE6AD1C0DA4BEC0 我想要的是,我需要編寫 smth,它的工作原理如下:當我從同一頁面按下任何食譜名稱時,我希望它將用戶引導到包含該食譜詳細信息(例如成分)的頁面,方法等。這些詳細信息將從名為 www.forexample.com/recipedetails/{id} 的 url 調用所以我希望它獲取點擊的食譜 ID 並將其添加到 url。 我該怎么做? 如何將第一個 url 數據中的 ID 傳遞給第二個 URL? 請幫忙:(

這是 my.service 文件:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';


const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

const apiUrl = "https://forexample.com/recipeslist";
@Injectable({
  providedIn: 'root'
})
export class ApiLandingRecipesService {

  constructor(private http: HttpClient) { }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError('Something bad happened; please try again later.');
  }

  private extractData(res: Response) {
    let body = res;
    return body || [] ; }

  getDataUser(): Observable<any> {
    return this.http.get(apiUrl, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }


}

這是我的 homepage.ts 文件:

import { ApiLandingRecipesService} from '../api-landing-recipes.service'

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.page.html',
  styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
  datauser: any[];
  constructor( public api: ApiLandingRecipesService) { }

  ngOnInit() {
    this.getDataUser();
  }
  async getDataUser() {
    await this.api.getDataUser()
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

這是我的主頁。html 文件:

<ion-card-header *ngFor="let data of datauser"> 
<p> {{data.recipename}} </p> 
</ion-card-header>

首先將您的 api url 更改為:

const apiUrl = "https://forexample.com/";

第二個改變這個:

getDataUser(uri): Observable<any> {
    return this.http.get(apiUrl + uri, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }

第三次在主recipies頁面中更改它:

ngOnInit() {
    this.getDataUser();
  }

async getDataUser() {
    await this.api.getDataUser('recipeslist')
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

現在在 html 的接收更改為:

<ion-card-header *ngFor="let data of datauser" routerLink="/detailspage/{{data.recipeid}}"> 
<p> {{data.recipename}} </p> 
</ion-card-header>

現在在 app-routing.module.ts 添加這個:

{ path: 'details/:id', loadChildren: ...' }

現在在詳細信息頁面:

import { ActivatedRoute } from '@angular/router'; 
recordId = null;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
    this.recordId = this.activatedRoute.snapshot.paramMap.get('id');
    this.getDataUser(this.recordId);
  }

async getDataUser(recordId) {
    await this.api.getDataUser('recipeslist/' + recordId)
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

我放了不同的頁面名稱,因為我不明白你的 class 命名是主頁(主頁或收據或登陸),但我寫 coupd 的方式對你來說更清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM