Issue
I'm building an ionic recipe app, the home page is calling a list of recipes names, ids and images using an API url which is www.forexample/recipeslist.com. The thing that I want is, I need to write smth which works as the following: When I press on any recipe name from that same page, I want it to direct the user to a page that contains that recipes details such as the ingredients, methods, etc .. These details will be called from a url named www.forexample.com/recipedetails/{id} So i want it to take the clicked recipe's ID and add it to that url. How can I do it? How can I pass the ID from the first url's data to the second URL? Please help:(
Here's my .service file:
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));
}
}
Here's my homepage.ts file:
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);
});
}
Here's my homepage.html file:
<ion-card-header *ngFor="let data of datauser">
<p> {{data.recipename}} </p>
</ion-card-header>
Solution
First change your api url to :
const apiUrl = "https://forexample.com/";
Second change this:
getDataUser(uri): Observable<any> {
return this.http.get(apiUrl + uri, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
Third change this in the main recipies page:
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);
});
}
Now in html of recepies change to:
<ion-card-header *ngFor="let data of datauser" routerLink="/detailspage/{{data.recipeid}}">
<p> {{data.recipename}} </p>
</ion-card-header>
Now in app-routing.module.ts add this:
{ path: 'details/:id', loadChildren: ...' }
Now in details page :
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);
});
}
I put different names of pages since i didn't understand your class naming for which is main page (home or receipies or landing) but the way i wrote coupd be clearer for you.
Answered By - Mostafa Harb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.