I'm new in Angular and I have an error need to fix. This is the error I've encountered when I'm trying to display a list of data from jsonplaceholder. I don't know what is wrong in the code. May I ask for a help guys? Thank you.
ERROR TypeError: Cannot read property '0' of undefined at RecipeService.push../src/app/recipes/recipe.service.ts.RecipeService.getRecipe (recipe.service.ts:25) at SafeSubscriber._next (recipe-detail.component.ts:26) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77) at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/BehaviorSubject.js.BehaviorSubject._subscribe (BehaviorSubject.js:22) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject._trySubscribe (Subject.js:89) at BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29)
recipe-detail.component.ts
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id = +params['id'];
this.recipe = this.recipeService.getRecipe(this.id);
}
);
}
recipe.service.ts
@Injectable()
export class RecipeService {
recipesChanged = new Subject<Recipe[]>();
private url = "https://jsonplaceholder.typicode.com/users/";
private recipes: Recipe[];
constructor(private slService: ShoppingListService, private http: Http) {}
getRecipes() {
return this.http.get(this.url).pipe(map(res => res.json()));
}
getRecipe(index: number) {
return this.recipes[index];
}
recipe-detail.component.html
<div class="row">
<div class="col-xs-12" *ngFor="let recipe of recipes">
<h1 class="list-group-item-heading">{{ recipe.id }}</h1>
<h4 class="list-group-item-heading">{{ recipe.name }}</h4>
<h4 class="list-group-item-heading">{{ recipe.username }}</h4>
<h4 class="list-group-item-heading">{{ recipe.email }}</h4>
<h4 class="list-group-item-heading">{{ recipe.phone }}</h4>
</div>
</div>
getRecipes()
? – SeleMHttp
inconstructor(private slService: ShoppingListService, private http: Http) {}
toHttpClient
: read about it here – dream88