Angular2 http GET请求有问题

时间:2017-04-19 10:45:24

标签: angular typescript

问题解决了

我没有注意到我需要为get请求添加选项。现在它工作得很好。 案件可以关闭。谢谢


我试图向我在本地运行的服务器发出一个http get请求但是无法让它工作..一直在尝试遵循许多教程但是,没有任何作用如此...我来找你,因为我有不知道出了什么问题:\
它运行并编译,但每当它达到要点时,它需要发出get请求,它似乎只是跳过它并继续,将visitorDetails对象保留为undefined。 我是Angular的新手,它是我的第一个应用程序,所以如果我对结构有其他问题或者你有什么建议 - 请告诉我。
我非常感谢你的帮助,提前谢谢!

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
        ){}
}

1 个答案:

答案 0 :(得分:0)

尝试:

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