2017-11-03 1 views
-3

안녕하세요,각도 2/4 | 토큰을 사용하여 API 데이터를 얻는 방법

각도 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 데이터를 얻는가? 도와 주셔서 감사합니다.

답변

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

이 흐름 내 나쁜, 난 내 치아 교정기를 검토 didnt하는 데 도움이 -, - 그것은 일 경우 –

+0

@JydonMah 답변을 받아 주시기 바랍니다. –

+0

예, TS1005 오류가 발생했습니다 : ';' 당신은 어떻게 ths를 고치는 지 압니까? –

관련 문제