代码之家  ›  专栏  ›  技术社区  ›  weinde

Angular 18@用于返回错误类型错误:newCollection[Symbol.iterator]不是函数

  •  1
  • weinde  · 技术社区  · 2 月前

    我决定开始使用最新的Angular版本(Angular 18.1),到目前为止,我使用的是版本7到14。。。

    我只是试着制作一个小虚拟应用程序来展示一系列电影。。。

    我做了一个非常基本的服务,它从API获取一些数据,并在html中的列表中显示这些数据。。。

    我决定在最新的angular版本中使用新的@作为语法,但现在我遇到了这个错误: ERROR TypeError: newCollection[Symbol.iterator] is not a function

    这与新版本的nagular有关吗?还是我失明了,忽略了我代码中的一个问题?

    编辑:Console.log正常工作。

    以下是component.ts代码:

    export class MovielistComponent implements OnInit{
      movies: movie[] = [];
      constructor(
        private movieService: GetMoviesService,
      ) { }
      ngOnInit() {
        this.getMoviesList();
      }
    
      getMoviesList() {
        this.movieService.getMovies().subscribe(
          data => {
            this.movies = data;
            console.log('Movies: ', this.movies);
          }
        )
      }
    
    }
    

    这是html文件代码:

    <ul>
      @for (movie of movies; track movie.attributes) {
        <li>{{ movie.attributes.name }}</li>
      } @empty {
        <li>There are no items.</li>
      }
    </ul>
    

    以下是model.ts代码:

    export interface movie {
      id: number,
      attributes: {
        name: string,
        imageUrl: string,
        synopsis: string,
        year: string,
        genre: string,
      }
    }
    

    根据要求,以下是API的回复:

    {
        "data": [
            {
                "id": 1,
                "attributes": {
                    "name": "The Shawshank Redemption",
                    "imageUrl": "https://m.media-amazon.com/images/M/MV5BNDE3ODcxYzMtY2YzZC00NmNlLWJiNDMtZDViZWM2MzIxZDYwXkEyXkFqcGdeQXVyNjAwNDUxODI@._V1_FMjpg_UY1800_.jpg",
                    "synopsis": "Over the course of several years, two convicts form a friendship, seeking consolation and, eventually, redemption through basic compassion.",
                    "year": "1994",
                    "genre": "drama",
                    "createdAt": "2024-07-16T12:34:06.769Z",
                    "updatedAt": "2024-07-16T12:36:29.952Z",
                    "publishedAt": "2024-07-16T12:36:29.951Z"
                }
            },
            {
                "id": 2,
                "attributes": {
                    "name": "The Godfather",
                    "imageUrl": "https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_FMjpg_UY1982_.jpg",
                    "synopsis": "Don Vito Corleone, head of a mafia family, decides to hand over his empire to his youngest son, Michael. However, his decision unintentionally puts the lives of his loved ones in grave danger.",
                    "year": "1972",
                    "genre": "crime, drama",
                    "createdAt": "2024-07-16T12:36:14.143Z",
                    "updatedAt": "2024-07-16T12:36:15.723Z",
                    "publishedAt": "2024-07-16T12:36:15.720Z"
                }
            },
            {
                "id": 3,
                "attributes": {
                    "name": "The Dark Knight",
                    "imageUrl": "https://m.media-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_FMjpg_UY2048_.jpg",
                    "synopsis": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.",
                    "year": "2008",
                    "genre": "action, crime, drama, thriller",
                    "createdAt": "2024-07-22T09:37:42.564Z",
                    "updatedAt": "2024-07-22T09:38:19.346Z",
                    "publishedAt": "2024-07-22T09:38:19.343Z"
                }
            }
        ],
        "meta": {
            "pagination": {
                "page": 1,
                "pageSize": 25,
                "pageCount": 1,
                "total": 3
            }
        }
    }
    
    2 回复  |  直到 2 月前
        1
  •  1
  •   Naren Murali    2 月前

    您还可以为来自API的响应添加接口。

    export interface Pagination{
        page: number;
        pageSize: number;
        pageCount: number;
        total: number;
    }
    
    export interface GetMoviesResponse {
        data: movie[];
        meta: Pagination;
    }
    

    您必须访问 data 响应中的属性,即数组。

    通常,当我们尝试在ngFor或@for上使用对象时,会出现此错误 ERROR TypeError: newCollection[Symbol.iterator] is not a function

    export class MovielistComponent implements OnInit{
      movies: movie[] = [];
      constructor(
        private movieService: GetMoviesService,
      ) { }
      ngOnInit() {
        this.getMoviesList();
      }
    
      getMoviesList() {
        this.movieService.getMovies().subscribe(
          (data: GetMoviesResponse) => {
            this.movies = data.data; // changed here!
            console.log('Movies: ', this.movies);
          }
        )
      }
    
    }
    
        2
  •  1
  •   brk    2 月前

    您需要访问 data 财产。您重命名的参数 subscribe response 了解差异。

    你也不能使用 inject 而不是 constructor 注入服务。你也应该 unsubscribe 订阅者`

    export class MovielistComponent implements OnInit {
      movies: movie[] = [];
      private destroyRef = inject(DestroyRef);
      private movieService = inject(GetMoviesService)
    
      ngOnInit() {
        this.getMoviesList();
      }
    
      getMoviesList() {
        this.movieService.getMovies().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(
          (response:{[key:string]:value}) => {
            this.movies:  = response['data'] || [];
            console.log('Movies: ', this.movies);
          }
        )
      }
    
    }
    
    <ul>
      @for (movie of movies; track movie.id) {
      <li>{{ movie.attributes.name }}</li>
      } @empty {
      <li>There are no items.</li>
      }
    </ul>