【问题标题】:Data type error when fetching data from backend从后端获取数据时出现数据类型错误
【发布时间】:2022-01-13 17:13:34
【问题描述】:

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});
    }
   
}

console.log(数据)

(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)

【问题讨论】:

  • 能否也显示api.service.ts中的代码?
  • 好的,在这种情况下,看看getMovies() 的实现会有所帮助。
  • 您是否编辑过问题?我没有看到任何新东西。
  • 好的,现在完成,代码已编辑。
  • 目前还不清楚getMovies返回什么类型(get没有任何类型规范),但它似乎很可能返回一个对象Observable > 某种,你期待一个数组。也许您想要的数组是该对象内的某个属性。在this.movies = data; 处设置调试断点或执行console.log,看看data 究竟是什么。

标签: angular13


【解决方案1】:

我的应用缺少一个 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});
    }

【讨论】:

  • 这看起来不错。
猜你喜欢
  • 2020-09-15
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
相关资源
最近更新 更多