API调用未从Angular 2 UI击中控制器

问题描述 投票:0回答:1

当通过http.get()从angular 2调用URL时,它将发生异常,并且不会在控制器中命中调试器。我更改了代理,检查了路由,但与我现有项目的路由相同。我刚刚添加了这个项目,这引起了问题。

基本上是Angular UI,在后端,我有Web apicontroller调用来获取与整个解决方案中其他现有项目相同的数据。

请在下面找到代码:

Component.ts

ngOnInit() {
        this.showpopup = true;
        this.getContent();
    }

getContent() {
        this.myService.getContent()
            .subscribe(
                response => {
                    this.showpopup = false;
                    this.contentList = response;

                },
                err => {
                    this.showpopup = false;
                    this.displayAlert("Error getting content.", this.errorAlert);
                }
            );
    }

Service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { MyProject} from '../models/interfaces/server-interfaces';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

export class MyService{
    public BASE_URL = 'api/myApp/';
    constructor(public http: Http) { }

    getContent(): Observable<MyProject.ProjectContent[]> {
        return this.http.get(this.BASE_URL + 'ProjectContentList')
            .map(response => response.json())
            .catch(err => Observable.throw(err));
    }
}

Controller.cs

    [RoutePrefix("api/myApp")]
    public class MyAppControllerController : ApiController
    {
        [Route("ProjectContentList")]
        [HttpGet]
        public async Task<HttpResponseMessage> GetContentAsync()
        {
            HttpResponseMessage response;

            try
            {
                //code here
            }
            catch (Exception ex)
            {
                //exception handled here
            }
            return response;
        }
}

我是Angular的新手。我有什么想念的吗?任何帮助将不胜感激。

angular typescript api asp.net-web-api angular2-services
1个回答
0
投票

在服务中。更改

来自:

constructor(public http: Http) { }

至:

constructor(public http: HttpClient)

您的模块应如下所示:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }   from './app.component';
import {HttpClientModule  } from '@angular/http';

@NgModule({
    imports:      [ BrowserModule, FormsModule, HttpClientModule  ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

看一下HttpClientModule的导入位置。那样做,它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.