2017-10-29 103 views
0

我有一個ASP.NET MVC項目,它使用ASP.NET WebAPI和Angular作爲UI組件。我對Angular相當陌生,所以請耐心等待。下面是我的項目中的配置文件。爲什麼在localhost中使用Angular時,http請求無法加載資源?

package.json文件

{ 
    "name": "angular-quickstart", 
    "version": "1.0.0", 
    "description": "QuickStart package.json from the documentation, supplemented with testing support", 
    "scripts": { 
    "build": "tsc -p src/", 
    "build:watch": "tsc -p src/ -w", 
    "build:e2e": "tsc -p e2e/", 
    "serve": "lite-server -c=bs-config.json", 
    "serve:e2e": "lite-server -c=bs-config.e2e.json", 
    "prestart": "npm run build", 
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"", 
    "pree2e": "npm run build:e2e", 
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first", 
    "preprotractor": "webdriver-manager update", 
    "protractor": "protractor protractor.config.js", 
    "pretest": "npm run build", 
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", 
    "pretest:once": "npm run build", 
    "test:once": "karma start karma.conf.js --single-run", 
    "lint": "tslint ./src/**/*.ts -t verbose" 
    }, 
    "keywords": [], 
    "author": "", 
    "license": "MIT", 
    "dependencies": { 
    "@angular/common": "~4.3.4", 
    "@angular/compiler": "~4.3.4", 
    "@angular/core": "~4.3.4", 
    "@angular/forms": "~4.3.4", 
    "@angular/http": "~4.3.4", 
    "@angular/platform-browser": "~4.3.4", 
    "@angular/platform-browser-dynamic": "~4.3.4", 
    "@angular/router": "~4.3.4", 

    "angular-in-memory-web-api": "~0.3.0", 
    "systemjs": "0.19.40", 
    "core-js": "^2.4.1", 
    "rxjs": "5.0.1", 
    "zone.js": "^0.8.4" 
    }, 
    "devDependencies": { 
    "concurrently": "^3.2.0", 
    "lite-server": "^2.2.2", 
    "typescript": "~2.1.0", 

    "canonical-path": "0.0.2", 
    "tslint": "^3.15.1", 
    "lodash": "^4.16.4", 
    "jasmine-core": "~2.4.1", 
    "karma": "^1.3.0", 
    "karma-chrome-launcher": "^2.0.0", 
    "karma-cli": "^1.0.1", 
    "karma-jasmine": "^1.0.2", 
    "karma-jasmine-html-reporter": "^0.2.2", 
    "protractor": "~4.0.14", 
    "rimraf": "^2.5.4", 

    "@types/node": "^6.0.46", 
    "@types/jasmine": "2.5.36" 
    }, 
    "repository": {} 
} 

systemjs.config.js文件

/** 
* System configuration for Angular samples 
* Adjust as necessary for your application needs. 
*/ 
(function (global) { 
    System.config({ 
     //baseURL: '/', 
     paths: { 
      // paths serve as alias 
      'npm:': 'node_modules/' 
     }, 
     // map tells the System loader where to look for things 
     map: { 
      // our app is within the app folder 
      'app': 'app', 

      // angular bundles 
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js', 
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js', 
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', 
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', 
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', 
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js', 
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js', 
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 

      // other libraries 
      'rxjs': 'npm:rxjs', 
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js' 
     }, 
     // packages tells the System loader how to load when no filename and/or no extension 
     packages: { 
      app: { 
       main: './main.js', 
       defaultExtension: 'js' 
       //meta: { 
       // './*.js': { 
       //  loader: 'systemjs-angular-loader.js' 
       // } 
       //}, 
      }, 
      rxjs: { 
       defaultExtension: 'js' 
      } 
     } 
    }); 
})(this); 

main.ts文件

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 
import { enableProdMode } from '@angular/core'; 
import { AppModule } from './app.module'; 

// Enable production mode unless running locally 
//if (!/localhost/.test(document.location.host)) { 
// enableProdMode(); 
//} 

platformBrowserDynamic().bootstrapModule(AppModule); 

app.routing.ts文件

import { ModuleWithProviders } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
import { HomeComponent } from './Components/home.component'; 

const appRoutes: Routes = [ 
    { path: '', redirectTo: 'home', pathMatch: 'full' }, 
    { path: 'home', component: HomeComponent } 
]; 

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); 

app.module.ts文件

import { NgModule } from '@angular/core'; 
import { APP_BASE_HREF } from '@angular/common'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 
import { AppComponent } from './app.component'; 
import { routing } from './app.routing'; 
import { HomeComponent } from './Components/home.component'; 
import { ChangeService } from './Services/changes.service'; 

@NgModule({ 
    imports: [BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, routing], 
    declarations: [AppComponent, HomeComponent], 
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService], 
    bootstrap: [AppComponent] 
}) 
export class AppModule {} 

changes.service.ts文件

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

@Injectable() 
export class ChangeService { 
    constructor(private _http: Http) { } 

    get(url: string) { 
     return this._http.get(url); 
    } 
} 

app.component.ts文件

 import { Component, ElementRef, OnInit } from '@angular/core'; 
    import { ChangeService } from './Services/changes.service'; 

    @Component({ 
     selector: 'moc-landing', 
     templateUrl: './app/Components/home.component.html', 
     styleUrls: ['./app/Components/home.component.css'] 
    }) 
    export class AppComponent implements OnInit { 
     maintitle: string; 
     statusList: IStatus[]; 
     showByList: IShowBy[]; 
     msg: string; 

     constructor(private elementRef: ElementRef, private _changeService: ChangeService) { 
      this.maintitle = this.elementRef.nativeElement.getAttribute('maintitle'); 
     } 

     ngOnInit() { 
      this.LoadStatus(); 
      this.LoadShowBy(); 
     } 

     LoadStatus(): void { 
this._changeService.get('http://localhost:56534/api/MoC/GetStatuses').subscribe(response => { this.statusList = response.json(); }); 
     } 

     LoadShowBy(): void { 
this._changeService.get('http://localhost:56534/api/MoC/GetShows').subscribe(response => { this.showByList = response.json(); });    
     }   
    } 

而且在我WebApiConfig.cs,內部的靜電Register方法,我也更新routeTemplate如下。

// Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

我的問題是,當我運行從Visual Studio 2017年上http://localhost:5653的應用;我得到Failed to load resource: the server responded with a status of 400 (Bad Request)

當我看到瀏覽器的控制檯,這是我得到了什麼, enter image description here

我直接在瀏覽器的地址欄http://localhost:56534/api/MoC/GetStatuses測試http請求,它給我的json數據,我需要。所以,在WebAPI方面沒有問題。

我發現這個SO post,並試圖遵循Praveen M答案,但它並沒有爲我工作。

爲什麼我得到(400)錯誤的請求?,我錯過了app.routing.ts中的重要配置嗎?

請問,任何人在這裏心地善良可以給我一個硬幣?

+0

_.subscribe(節目=> {this.showByList =顯示},錯誤=> this.msg = 錯誤); _爲什麼訂閱逗號? –

+0

@RahulSingh無所謂了。我已將該行更改爲此this._changeService.get('http:// localhost:56534/api/MoC/GetShows').subscribe(response => {this.showByList = response.json();}); '但我仍然得到了Http 400的錯誤請求。 – Juniuz

+0

從組件調用中刪除.json,您已經在服務 –

回答

0

嘗試改變:

providers: [{ provide: APP_BASE_HREF, useValue: '/' }, ChangeService] 

只是:

providers: [ChangeService] 
+0

好吧,我試過了,但仍然沒有工作:( – Juniuz

0

好了,敲我的頭掛在牆上後。我發現了這個問題的罪魁禍首。這是我的一個愚蠢的錯誤。這個問題不在與本地主機無關的http請求上。它是組件元數據templateUrl之一。我錯誤的聲明像這樣templateUrl: '<span>Hello</span>',而不是僅僅template: '<span>Hello</span>'

這就是爲什麼應用程序將引發異常,因爲組件模板是在惡劣形式http://localhost:56534/%0A%20%20%20%20

相關問題