Я совершенно новый для Angular, и я пытаюсь сделать простой HTTP-запрос данных. Как получить доступ к этим данным в моем компоненте? Я получаю сообщение об ошибке 'Не могу прочитать свойство' get 'of undefined'
data.service.ts
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
@Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).subscribe(data => {
console.log(data)
})
}
}
table.component.ts
import { FetchData } from './datatable.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
Data: FetchData
constructor() { }
ngOnInit() {
this.Data.get()
}
}
Вам необходимо "Ввести" службу в свой компонент, а также сделать подписку в своем компоненте.
В вашем сервисе вы должны "отобразить" свой ответ.
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import 'rxjs/add/operator/map';
@Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).map(data => {
return data.json();
})
}
}
Ваш компонент:
import { FetchData } from './datatable.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
constructor(private fetchDataService: FetchData) { }
ngOnInit() {
this.fetchDataService.get().subscribe(res => {
console.log(response);
});
}
}
попробуй это:
export class DatatableComponent implements OnInit {
constructor(private dataService: FetchData) { }
ngOnInit() {
this.dataService.get()
}}