cmelion / generator-ng2-webpack

An opinionated tool for scaffolding an app using angular2 and webpack
MIT License
109 stars 18 forks source link

http issue #62

Closed itranga closed 8 years ago

itranga commented 8 years ago

I am getting an error when I am using below code to access rest API,

ORIGINAL EXCEPTION: TypeError: platform_browser_1.platform_browser_private.getDOM(...).getCookie is not a function

import {Component, OnInit, Injectable} from '@angular/core'; import {FORM_DIRECTIVES} from '@angular/common'; import {Http, Headers} from '@angular/http';

import {Api} from '../../services/api';

@Component({ selector: 'home', directives: [...FORM_DIRECTIVES], providers: [Api], pipes: [], styles: [require('./style.scss')], template: require('./template.html') }) @Injectable() export class Home implements OnInit {

constructor(http: Http) {
    this.http = http;
}

createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
        btoa('username:password'));
}

getRandom() {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get('http://localhost:3000/items', {
        headers: headers
    });
}

post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post('http://localhost:3000/items', data, {
        headers: headers
    });
}

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

}

but when I use below code it works perfectly.

fetch('http://localhost:3000/items').then((response) => { return response.json(); }).then((data) => {

        console.log(data);

    }).catch((ex) => {
        console.error('Error fetching users', ex);
    });

but I want to use 1st function since I have to pass header values.

How can I solve it.

Thanks

cmelion commented 8 years ago

The example at https://github.com/cmelion/ng2-webpack-demo-app/blob/master/src/app/services/api/items/index.ts passes a header value on post and is part of a working example covering CRUD operations. If you are willing to refactor your code into an redux/rx style I can likely be of assistance.

itranga commented 8 years ago

I try to install your demp app [ https://github.com/cmelion/ng2-webpack-demo-app ] . Got the same issue getcookie-notfunction

itranga commented 8 years ago

I found the solution . Please change "@angular/http": "^2.0.0-rc.1", to "@angular/http": "2.0.0-rc.1", in package.json

cmelion commented 8 years ago

I see. The generator is currently using rc.3 and your package.json is still referencing rc.1 so you were getting a later version of the http dependency. I have removed the caret(^) and the dependency now reads as "@angular/http": "2.0.0-rc.3".