2

Problem solved

I didn't notice I need to add options to the get request. Now it works just fine. Case can be closed. Thanks



I'm trying to make an http get request to a server I run locally but can't get it working.. been trying to follow many tutorials and yet, nothing works so.. i come to you since i have no idea what is wrong :\
It runs and compiles, but whenever it gets to the point it needs to make the get request it seems like it just skips it and continue, leaving the visitorDetails object undefined.
I'm new to Angular and it's my first app so if i have other problems with the structure or if you have anything to recommend - please do tell me.
I really appreciate the help, thanks in advance!

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

app.module.ts:

import { NgModule }     from '@angular/core';
import { BrowserModule }from '@angular/platform-browser';
import { FormsModule }  from '@angular/forms';
import { HttpModule }   from '@angular/http';

import { AppComponent }  from './app.component';

@NgModule({
    imports:      [ 
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})

export class AppModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

import { DataService } from './dataservice.service';
import { VisitorDetails } from './visitordetails';


@Component({
    selector: 'my-app',
    template: `
    <h1> {{title}} </h1>
    <h2> text: {{visitorsText}} </h2>
    `,
    providers: [DataService]
})

export class AppComponent implements OnInit {
    title = 'TrafficerData';
    visitorsText = this.getData();
    errorMessage: string;
    visitorDetails: VisitorDetails;

    constructor (private dataService: DataService) {}

    ngOnInit() { 
        this.getData();
    }

    getData() : VisitorDetails {
        this.dataService.getData()
                        .subscribe(
                            val     => this.visitorDetails = val,
                            error   => this.errorMessage = <any>error);

        return this.visitorDetails;
    }
}

app.service.ts:

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

import { Observable }       from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { VisitorDetails } from './visitordetails';

@Injectable()
export class DataService {

    constructor (private http: Http) {}

    getData(): Observable<VisitorDetails> {
        return this.http.get('http://localhost:8000/api/client01/visitors')
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

visitordetails.ts:

export class VisitorDetails {
    constructor(
        public numOfVisitors: string,
        public numOfBlockers: string,
        public blockingPercentage: string
        ){}
}
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44
Ben. N
  • 21
  • 4
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – eko Apr 19 '17 at 10:54
  • The things you didn't include in your question are any error messages you see in the console. – R. Richards Apr 19 '17 at 10:54
  • I didn't include any error messages since I don't have any errors. It runs normally but don't behave as expected due to a reason I can't figure out. I checked out the possibility for duplicate and it's not, but I found my problem over there - i didn't add the options for the get request. Now it works and the case can be closed. Thanks! – Ben. N Apr 19 '17 at 11:48

1 Answers1

0

Try:

getData(): Observable<VisitorDetails> {
    return this.http.get('http://localhost:8000/api/client01/visitors')
                    .map(res => this.extractData(res))
                    .catch(this.handleError);
}
Emerceen
  • 2,735
  • 3
  • 17
  • 22
  • Thanks Emerceen but it was a different issue :) I just forgot to add an options object to the call – Ben. N Apr 19 '17 at 12:19