0

Angular 抛出以下错误:

“‘Object’类型缺少‘never[]’类型的以下属性:length、pop、push、concat 等 28 个。

this.movi​​es = 数据;"

// movie-list.component.ts

// ...

export class MovieListComponent implements OnInit {

  movies = [];

  constructor(
    private apiService: ApiService) { }

  ngOnInit() {
    this.apiService.getMovies().subscribe(
      data => {
        this.movies = data;
      })}
}

我已经将“电影”变量更改为

movies: any[] = [];

但错误仍然出现

// api.service.ts

// ...
export class ApiService {

  baseUrl = 'http://127.0.0.1:8000/api/movies/'
  headers = new HttpHeaders({
    'Content-Type': 'application/json',
    Authorization: 'token 61a1e3bfcfaea4fceee08d52fa132c788204d5e4'
  })

  constructor(
    private http: HttpClient
  ) {}

    getMovies() {
      return this.http.get(this.baseUrl, {headers: this.headers});
    }
   
}

控制台日志(数据)

(3) [{…}, {…}, {…}]
0: {id: 1, title: 'Titanic', description: 'Romantic movie '}
1: {id: 2, title: 'Avatar', description: 'SiFy movie'}
2: {id: 4, title: 'Dune', description: 'SiFy movie'}
length: 3
[[Prototype]]: Array(0)
4

1 回答 1

0

我的应用缺少一个 movie.ts 文件:

export interface Movie {
    id?: any;
    title?: string;
    description?: string;
}

所以我不得不通过以下方式重构 getMovie 方法:

    getMovies(): Observable<Movie[]>{
      return this.http.get<Movie[]>(this.baseUrl, {headers: this.headers});
    }
于 2021-12-09T14:20:46.880 回答