billy_comic
billy_comic

Reputation: 899

HTTP PUT Request Returns Empty From Angular 2 Service

I'm calling data from a service. I have to pass in an object with properties to retrieve the data. From what I can tell, I'm passing it in correctly and not receiving any errors in console, but the object that I assign to the data is empty. I'm including my Service and Component where I'm outputting the data.

I call the exact same endpoint from an Angular1 App with the same "payload" values and get my data object returned. I'm sure I'm missing something simple. Still getting used to Angular 2.

SERVICE

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

}

Upvotes: 0

Views: 1487

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136164

Asynchronous operation doesn't work synchronous way. You have to wait until the ajax gets completed. You can only see a data inside subscription of your getQr function once the service call resolved.

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

Upvotes: 1

Related Questions