在angular 5中使httpClient.get时无法获取数据

时间:2018-08-31 20:42:21

标签: angular5 observable httpclient

我正在尝试使用httpclient做一个http.get。但是,我正在

  

ReferenceError:数据未定义

订阅服务方法时,在我的组件类内部。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

const httpOptions = {
  headers: new HttpHeaders()
    .set('Authorization', 'Bearer xxxxx')
    .set('Content-Type', 'application/json')
};


@Injectable()

export class SetsService {


  constructor(private http: HttpClient) { }




  getSet() {

    return this.http.get('http://localhost:1234/api/users', httpOptions);

  }
}

我的组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { SetsService } from '../services/sets.service';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-sets',
  templateUrl: './sets.component.html',
  styleUrls: ['./sets.component.scss']
})

export class SetsComponent implements OnInit {
  id: string = "";
  set: any = {};
  constructor(private route: ActivatedRoute, private router: Router, private _setsService: SetsService) {

    this.route.params.subscribe(res => this.id = res.id);
  }

  ngOnInit() {
    this.getSets();
  }

  getSets(){
    this._setsService.getSet().subscribe(
      (data) => { this.set = data },
      err => console.error(err),
      () => { console.log('done loading set') }
    );
  }}

当我查看网络时,API调用成功并返回数据。

在html里面,我只是想打印设置的对象。

0 个答案:

没有答案