从自己的api url读取数据并使用接口



我尝试从api服务器获取json数据。我无法将其添加到变量中。我得到错误

Type中缺少以下属性;可观察的";缺少类型"中的属性;GAMILIST[]":"length,pop,push,concat;和27 weitere.ts(2740(

我的错误在哪里?

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import gamelistjson from '../../assets/data/gamelist.json';
interface GAMELIST {
id: number,
title: string,
releasedate: number,
shortdescription: string,
adddate: string,
changedate: string,
tags: any
}
@Component({
selector: 'app-gamelist',
templateUrl: './gamelist.component.html',
styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {
private data:any = [];
games: GAMELIST[] = this.getJSON();
idspiel: number = 0;

constructor(private router: Router, private http: HttpClient) { 
this.getJSON().subscribe(data => {
console.log(data);
});
}
ngOnInit(): void {
}
public getJSON(): Observable<any> {
return this.http.get("https://example.org/api/gamelist");
}
onSelect(game: any){
this.router.navigate(['/spiel', game.id, game.title]);
}
}

我认为这是有问题的一行。

games: GAMELIST[] = this.getJSON();

this.getJson((返回一个observable,并且您正试图将observable分配给GAMILIST[]类型。您应该在订阅中分配它

这是更改后的代码;

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import gamelistjson from '../../assets/data/gamelist.json';
interface GAMELIST {
id: number,
title: string,
releasedate: number,
shortdescription: string,
adddate: string,
changedate: string,
tags: any
}
@Component({
selector: 'app-gamelist',
templateUrl: './gamelist.component.html',
styleUrls: ['./gamelist.component.css']
})
export class GamelistComponent implements OnInit {
private data:any = [];
games: GAMELIST[];
idspiel: number = 0;

constructor(private router: Router, private http: HttpClient) { 

}
ngOnInit(): void {
this.getJSON().subscribe(data => {
this.games = data;
});
}
getJSON(): Observable<GAMELIST[]> {
return this.http.get("https://example.org/api/gamelist");
}
onSelect(game: any){
this.router.navigate(['/spiel', game.id, game.title]);
}
}

如果上面的代码仍然有任何错误,请尝试更改一行games:GAMELIST[];

games:GAMELIST[]=[];

最新更新