2017-03-09 8 views
0

서비스에서 데이터를 호출하고 있습니다. 데이터를 검색하기 위해 속성이있는 객체를 전달해야합니다. 내가 말할 수있는 것부터, 올바르게 전달하고 콘솔에서 오류를받지 못하지만 데이터에 할당 한 객체가 비어 있습니다. 데이터를 출력 할 곳에서 서비스 및 구성 요소를 포함합니다.HTTP PUT 요청이 앵귤러 2 서비스에서 비어 있음

동일한 "페이로드"값을 가진 Angular1 App에서 정확히 동일한 끝점을 호출하고 내 데이터 객체를 반환합니다. 나는 간단한 것을 놓치고 있다고 확신한다. 아직 동기 방식으로 작동하지 않는 각도 2.

서비스

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class DataService { 
private qrDataUrl = 'http://my.data.url/endpoint'; 

private payload = { 
    DeliveryTypeId: 0, 
    PickupLocationid: 0, 
    PaymentTypeId: 0, 
    Items: ['XXXX'], 
    ApplicationToken:'123MYTOKEN456', 
    DateOfBirth: "1961-01-01T00:00:00.000Z" 
}; 

    constructor(private http: Http){ } 

    getQr():Observable<any>{ 
    return this.http.put(this.qrDataUrl, this.payload) 
    .map((res:Response) => res.json()); 
    } 
} 

COMPONENT

import { Component, OnInit } from '@angular/core'; 
import { DataService } from '../shared/dataService'; 

@Component({ 
    selector: 'my-home', 
    templateUrl: './home.component.html', 
    styleUrls: ['./home.component.scss'], 
    providers: [DataService] 
}) 
export class HomeComponent implements OnInit { 
    qrData = { }; 

    constructor(private dataService: DataService) { 
    // Do stuff 
    } 



    getData(){ 
    this.dataService.getQr().subscribe(data => this.qrData = data); 
    console.log(this.qrData); //This logs an empty object 
    } 

    ngOnInit() { 
    console.log('Hello Home'); 
    this.getData(); 
    } 

} 
+0

입니다. 그것의 비동기 호출. console.log는 나머지가 끝날 때까지 기다리지 않고 트리거됩니다. 이러한 문제를 피하기 위해 catch 또는 트릭을 사용하는 것은 간단한 작업 일 수 있습니다. 할당 할 때 한 줄 함수를 사용하지 마십시오. – Gary

답변

1

비동기 작업에 익숙해. 아약스가 완료 될 때까지 기다려야합니다. 서비스 호출이 해결되면 getQr 기능의 구독 내에서만 데이터를 볼 수 있습니다.

getData(){ 
    this.dataService.getQr().subscribe(data => { 
     this.qrData = data; 
     console.log(this.qrData); //This logs an empty object 
    }); 
} 
+0

완벽하게 작동합니다. 질문 : 데이터가 실제로 OP의 구문에서 반환 되었습니까? 그리고 데이터가 반환되기 전에 내 console.log()가 발생 했습니까? 또는 비동기 데이터를 검색하기 위해 {}을 (를) 포함하는 구문을 추가해야합니까? –

+0

예, 아작스가 완료되기 전에 콘솔 명령문이 동기 연산이므로 호출됩니다. 그리고 브라우저는 비동기 전에 동기 작업을 실행합니다. –