I want to fetch my data from Localhost on angular using Http and Observable this are my service
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');
}
}
I create this constructor so i can get it from everywhere
export interface IGames{id:number, name:string, description:string, pictute:string}
this is my 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;
}
);
}
}
this code work though but on my terminal it always shows this error
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'.
works for me just fine, with 2 changes: 1) move GamesComponent.games
declaration above constructor, and add type: games: IGames[] = [];
2) console.log=data should be 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);
}
);
}
}