Angular 2/4 |如何使用Token获取API数据

时间:2017-11-03 10:02:21

标签: angular typescript angular2-http

美好的一天,

如何使用角度2/4获取带有令牌的api数据?

这是我的代码:

import { Component, ViewEncapsulation } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {

private apiUrl = 'http://apiurlhere.xom/data';
data: any = {};

constructor(private http: Http){
    console.log('hi');
    this.getVoicepickData();
    this.getData();
}

//set API header
    let headers = new Headers({
        'Token': "XXXXXXXXXXTOKEN HEREXXXXXXXXXX",
        'Content-Type': 'application/json'
    });

    getData(){
        return this.http.get(this.apiUrl, {headers: headers})
            .map((res: Response) => res.json())
    }

    getVoicepickData() {
        this.getData().subscribe(data => {
            console.log(data);
            this.data = data
        })
    }
}

我收到错误说:模块解析失败:'返回'功能之外。可以有人如何使用令牌获取api数据?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您无法在功能范围之外设置变量。但是,您可以将其设置为公共属性或在函数getData内设置。

希望这有帮助

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {

private apiUrl = 'http://apiurlhere.xom/data';
data: any = {};
headers: Headers;

constructor(private http: Http){
    console.log('hi');
    this.getVoicepickData();
    this.getData();

    this.headers = new Headers({
        'Token': "XXXXXXXXXXTOKEN HEREXXXXXXXXXX",
        'Content-Type': 'application/json'
    });
}

    // YOU CANNOT SET SOMETHING HERE

    getData(){
        return this.http.get(this.apiUrl, {headers: this.headers})
            .map((res: Response) => res.json());
    }

    getVoicepickData() {
        this.getData().subscribe(data => {
            console.log(data);
            this.data = data
        });
    }
}