Angular 2-调用http与observable不起作用。尝试了所有选项,但没有奏效

时间:2017-06-07 18:14:34

标签: angular http dictionary observable

无法使用angular2中的http调用web api。 尝试了不同的解决方案但仍无济于事因此,开启新问题可能会对我有所帮助。

尝试了以下解决方案,但没有帮助:

http with Observable in Angular 2 cant use data

Angular2 - http.get not calling the webpi

why http.post didn't call my controller in angular 2

以下是来源 - 如果我做错了,请告诉我:

"的package.json"

{
  "name": "Angular2Spa",
  "version": "0.0.0",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@angular/router": "3.0.0",
    "@types/node": "^6.0.38",
    "angular2-localstorage": "^0.4.0",
    "angular2-platform-node": "~2.0.10",
    "angular2-universal": "~2.0.10",
    "angular2-universal-polyfills": "~2.0.10",
    "aspnet-prerendering": "^1.0.6",
    "aspnet-webpack": "^1.0.11",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "es6-shim": "^0.35.1",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.0.0-beta.12",
    "style-loader": "^0.13.0",
    "to-string-loader": "^1.1.5",
    "ts-loader": "^0.8.2",
    "typescript": "^2.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.14",
    "webpack-externals-plugin": "^1.0.0",
    "webpack-hot-middleware": "^2.10.0",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.6.21"
  }
}

" app.component.ts"

import { Component, Inject } from '@angular/core';

@Component({
    selector: 'app',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})
export class AppComponent {
}


"app.module.ts"

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
//declare var localStorage: any;
// used to create fake backend
import { fakeBackendProvider } from './components/_helpers/index';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, Http, HttpModule, Response } from '@angular/http';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { LoginComponent } from './components/login/index';
import { RegisterComponent } from './components/register/index';
import { AlertComponent } from './components/_directives/index';
import { AuthGuard } from './components/_guards/index';
import { AlertService, AuthenticationService, UserService, FetchDataService } from './components/_services/index';


@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        LoginComponent,
        RegisterComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        //HttpModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: 'register', component: RegisterComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        FetchDataService,
        // providers used to create fake backend
        fakeBackendProvider,
        MockBackend,
        BaseRequestOptions
    ],
})
export class AppModule {
}

" fetchdata.component.ts" (在此通话服务中)

import { Component, OnInit } from '@angular/core';
import { Http, Response, HttpModule } from '@angular/http';
import { Observable } from "rxjs/Observable";
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Router } from '@angular/router';
import { AlertService, FetchDataService } from "../_services/index";

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})


export class FetchDataComponent implements OnInit{
    public forecasts: WeatherForecast[];
    array = Array<any>();
    loading: boolean;

    private baseUrl: string = 'http://localhost:2828/';

    //private fetchDataService: FetchDataService;
    constructor(
        private router: Router,
        private fetchDataService: FetchDataService,
        private alertService: AlertService,
        private http: Http) {
        //TRY-1   
        //this.http.get(this.baseUrl + 'api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });


        //TRY-2
        //this.fetchDataService.getAll()
        //    .subscribe(
        //    data => {
        //        this.alertService.success('service called successfuly', true);
        //    },
        //    error => {
        //        this.alertService.error(error);
        //        this.loading = false;
        //    });

        //http.get('http://jsonplaceholder.typicode.com/photos/1')
        //    .map((res: Response) => res.json())
        //    .subscribe(res => {
        //        this.array = res;
        //        this.loading = false;
        //    });

        //TRY-3
        //http.get('/api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });
    }

    ngOnInit() {
        this.getMyData()
            .subscribe((res: any) => {
                console.log(res);
            },
            error => {
                // TODO: Error handling
                console.log(error);
            });
    }

    private getHeaders() {
        // I included these headers because otherwise FireFox
        // will request text/html instead of application/json
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }

    getMyData(): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)
            //.do(response => console.log("Result: " + JSON.stringify(response)))
            .map((res: Response) => {
                console.log(res);
                return res;
            })
            .catch((err) => {
                // TODO: Error handling
                console.log(err);
                return err;
            })
    };
}

如果有任何问题,请告诉我。

1 个答案:

答案 0 :(得分:1)

让你知道你得到了什么错误会很有帮助。 如果您想使用标题,请尝试更改

this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)`

this.http.get('http://jsonplaceholder.typicode.com/photos/1', { headers: headers })