【问题标题】:Having this error while displaying list of data in Angular => ERROR: TypeError: Cannot read property '0' of undefined在 Angular => 错误中显示数据列表时出现此错误:TypeError:无法读取未定义的属性“0”
【发布时间】:2019-04-17 10:39:09
【问题描述】:

我是 Angular 的新手,我有一个错误需要修复。这是我在尝试显示来自 jsonplaceholder 的数据列表时遇到的错误。我不知道代码中有什么问题。我可以寻求帮助吗?谢谢。

错误类型错误:无法读取未定义的属性“0” 在 RecipeService.push../src/app/recipes/recipe.service.ts.RecipeService.getRecipe (recipe.service.ts:25) 在 SafeSubscriber._next (recipe-detail.component.ts:26) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (订阅者.js:134) 在 Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (订阅者.js:77) 在 Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (订阅者.js:54) 在 BehaviorSubject.push../node_modules/rxjs/_esm5/internal/BehaviorSubject.js.BehaviorSubject._subscribe (BehaviorSubject.js:22) 在 BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43) 在 BehaviorSubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject._trySubscribe (主题.js:89) 在 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>

【问题讨论】:

  • 您使用的是哪个版本的 Angular?
  • @dream88 - 我目前正在使用 Angular 7
  • 你什么时候打电话给getRecipes()
  • 可能与您的问题无关,但您应该考虑将constructor(private slService: ShoppingListService, private http: Http) {} 中的Http 更改为HttpClientread about it here
  • @selemmn - 从 jsonplaceholder 获取数据,但错误在 getRecipe 方法中

标签: json angular routing frontend


【解决方案1】:

可能是配方为空/未定义。因此,当您调用 getRecipe(0) 时会出现此错误。尝试将您的方法更改为以下内容:

getRecipe(index: number) {
    if (!!this.recipes && this.recipes.length > index) {
       return this.recipes[index];
    } else {
       return 0; //Whatever
    }
}

【讨论】:

  • 错误现在不显示但来自 jsonplaceholder 的数据也没有显示
【解决方案2】:

在组件中,您将 id 传递给服务的 getRecipe() 方法。但是,您不能确定它是否存在,这就是它发生的原因。此外,在服务中,“食谱”从何而来?您对其进行初始化,但从不为其分配任何值(尤其是作为数组)。即,您根本没有调用 getRecipes()。

所以改变服务:

getRecipe(index: number) {
  return this.recipes[index] ? this.recipes[index] : null;
}

所以现在在您的组件中 this.recipe 可能等于 'null' 但您不会收到错误消息。

【讨论】:

    【解决方案3】:

    private recipes: Recipe[] 未在此处初始化。在访问元素之前,您必须检查 undefinedlength

    组件

    getRecipe(index: number) {
        if(this.recipes && this.recipes.length > index){
            return this.recipes[index];
        }else{
           return null;
        }
    

    }

    食谱服务

    @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) {
          this.getRecipes().subscribe(recipes=>this.recipes); //<-- you may call from somewhere else.
      }
    
      getRecipes() {
        return this.http.get(this.url).pipe(map(res => res.json()));
      }
    
      getRecipe(index: number) {
        return this.recipes[index];
      }
    

    【讨论】:

    • 错误现在不显示但来自 jsonplaceholder 的数据也没有显示
    • 您应该致电getRecipes 获取食谱。我更新了答案。我调用了构造函数,但你也可以从其他地方初始化。
    猜你喜欢
    • 2023-02-26
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多