【问题标题】:Angular 2- calling http with observable not working. tried all option but not workedAngular 2-用可观察的方式调用 http 不起作用。尝试了所有选项但没有奏效
【发布时间】:2017-11-09 05:47:13
【问题描述】:

无法在 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;
            })
    };
}

如果有什么问题请告诉我。

【问题讨论】:

  • 你应该将你的 http 代码分离到它自己的服务中。我也建议清理这篇文章。它有点难以阅读。只需包括相关信息。可能不需要所有 package.json 信息和/或过去的失败尝试。只是您正在努力的当前尝试。另请查看您是否可以在plnkr.co 中重现该问题,这将有助于其他人了解问题所在。
  • 每次尝试会出现什么错误
  • 错误是什么?
  • 没有错误,但即使在浏览器的网络中,get 似乎也没有通过,我找不到调用的 get url。
  • 从您的模块中删除所有虚假的后端内容。它们会干扰您真正的 http 请求。另外,就像克里斯所说的那样。为您的 http 请求提供单独的服务。我还看到您的代码存在其他一些问题,例如此处不需要标头并尝试将 res 分配给您的变量。应该是res.json() 但是,是的,做一个服务,在那里做请求,订阅组件。我建议你看看official TOH tutorial for HTTP

标签: angular http dictionary observable


【解决方案1】:

告知您遇到了什么错误会很有帮助。 如果要使用标题,请尝试更改

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

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

【讨论】:

  • 感谢重播@Ashish。添加 {headers: headers} 显示错误:Build:Argument of type '{ headers: Headers; }' 不可分配给“RequestOptionsArgs”类型的参数。也试过不带标题..但还是不行。
  • 键标头的值应为标头(可变标头,而不是类型标头)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多