我想使用Http和Observable从Localhost上按角度获取数据,这是我的服务
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { HttpParams } from '@angular/common/http';
import { IGames } from './games';
@Injectable({
providedIn: 'root'
})
export class GamesService {
constructor(private http: HttpClient) { }
test():Observable<any>{
return of("test");
}
getGames():Observable<IGames[]>{
return this.http.get<IGames[]>('http://localhost/pmn/uas/getgames.php');
}
}
我创建了这个构造函数,以便可以从任何地方获取它
export interface IGames{id:number, name:string, description:string, pictute:string}
这是我的games.component.ts
import { Component, OnInit } from '@angular/core';
import { GamesService } from '../games.service';
import { IGames } from '../games';
@Component({
selector: 'app-games',
templateUrl: './games.component.html',
styleUrls: ['./games.component.css']
})
export class GamesComponent implements OnInit {
constructor(private gs:GamesService) { }
games=[];
ngOnInit() {
this.gs.getGames().subscribe(
(data)=>{
this.games=data;
console.log=data;
}
);
}
}
虽然此代码有效,但是在我的终端上它始终显示此错误
ERROR in src/app/games/games.component.ts(18,9): error TS2322: Type 'IGames[]' is not assignable to type '(message?: any, ...optionalParams: any[]) => void'.
Type 'IGames[]' provides no match for the signature '(message?: any, ...optionalParams: any[]): void'.
答案 0 :(得分:1)
对我来说很好,进行了2次更改:1)将GamesComponent.games
声明移到构造函数上方,并添加类型:games: IGames[] = [];
2)console.log = data应该为console.log(data);
>
export class GamesComponent implements OnInit {
// members should be above constructor
games: IGames = [];
constructor(private gs:GamesService) { }
ngOnInit() {
this.gs.getGames().subscribe(
(data)=>{
this.games=data;
// console.log is a function
console.log(data);
}
);
}
}