Http在Angular中作为服务调用

时间:2017-11-24 22:03:07

标签: javascript angular http

我是Angular的新手,我正在尝试为数据做一个简单的http请求。如何在组件中访问此数据?我收到错误'无法读取属性'获取'未定义'

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

}

2 个答案:

答案 0 :(得分:1)

您需要在组件中“注入”服务,并在组件中进行订阅。

在您的服务中,您应该“映射”您的回复。

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

}

答案 1 :(得分:0)

试试这个:

export class DatatableComponent implements OnInit {
constructor(private dataService: FetchData) { }

ngOnInit() {
  this.dataService.get()
}}