2016-04-12 60 views
1

我正在處理身份驗證頭,一種解決方案是創建一個子類從'angular2/http'擴展Http並添加默認的auth頭文件。我使用的是github中的相同代碼,但它會拋出 EXCEPTION: TypeError: backend.createConnection is not a function in [null] code here。但是當我將它改回到angular2/http時,一切正常。我找不到有關此異常消息的任何信息。感謝幫助!Angular2子類的Http拋出錯誤

更新: 我使用樣品的相同方式。 這是我的服務:

import {Injectable} from 'angular2/core'; 
// import {Http} from 'angular2/http'; 
import {Headers, Response} from 'angular2/http'; 
import {Http} from '../common/http'; 
import {Category} from '../model/category'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class CategoryService { 
    constructor(private http:Http) {} 
    getCategories() { 
     return this.http.get('http://www.google.com') 
     .map(res => res.json()); 
    } 

    getCategory(id: string) { 
     return this.http.get('http://localhost:8080/api/category/'+id) 
     .map(res => res.json()); 
    } 
} 

這是我的/黎民/ HTTP

import {Observable} from "rxjs/Observable"; 
import {Injectable} from "angular2/core"; 
import {Http as NgHttp, RequestOptionsArgs, RequestOptions, Headers, Response, ConnectionBackend} from "angular2/http"; 

const mergeAuthToken = (options:RequestOptionsArgs) => { 
    let newOptions = new RequestOptions({}).merge(options); 
    let newHeaders = new Headers(newOptions.headers); 
    let access_token = localStorage.getItem('access_token'); 
    newHeaders.set('Authorization', 'bearer '+ access_token); 
    newHeaders.set('Accept', 'application/json'); 
    newHeaders.set('Content-Type', 'application/json'); 
    newOptions.headers = newHeaders; 
    return newOptions; 
}; 

@Injectable() 
export class Http extends NgHttp { 
    constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions) { 
     super(_backend, _defaultOptions); 
    } 
    get(url:string, options?:RequestOptionsArgs):Observable<Response> { 
     return super.get(url, mergeAuthToken(options)); 
    } 

    post(url:string, body:string, options?:RequestOptionsArgs):Observable<Response> { 
    return super.post(url, body, mergeAuthToken(options)); 
    }... 
} 

這是我app.component的一部分:

import { Http } from '../common/http'; 
import { SecurityRouterOutlet } from '../router/securityRouter'; 
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; 
import {HTTP_PROVIDERS, ConnectionBackend } from 'angular2/http'; 

@Component({ 
    selector: 'my-app', 
    templateUrl: 'app/view/app.component.html', 
    styleUrls: ['app/view/app.component.css'], 
    directives: [SecurityRouterOutlet, ROUTER_DIRECTIVES], 
    providers: [ 
     ROUTER_PROVIDERS, 
     HTTP_PROVIDERS, 
     CategoryService, 
     LoginService, 
     ConnectionBackend, 
     Http 
    ] 
}) 

如果需要更詳細的代碼,請告訴我。謝謝!

UPDATE2作爲@Thierry TEMPLIER的建議,我將http更改爲AuthHttp在我的共同/ HTTP的文件等,服務類和app.component.ts,但這並不能幫助。

異常的完整的堆棧:

TypeError: backend.createConnection is not a function angular2.dev.js:23877 
    at httpRequest (http.dev.js:941) 
    at AuthHttp.Http.get (http.dev.js:980) 
    at AuthHttp.get (http.ts:24) 
    at CategoryService.getCategories (category.service.ts:16) 
    at DashboardComponent.ngOnInit (dashboard.component.ts:15) 
    at AbstractChangeDetector.ChangeDetector_HostDashboardComponent_0.detectChangesInRecordsInternal (viewFactory_HostDashboardComponent:21) 
    at AbstractChangeDetector.detectChangesInRecords (angular2.dev.js:9609) 
    at AbstractChangeDetector.runDetectChanges (angular2.dev.js:9592) 
    at AbstractChangeDetector._detectChangesContentChildren (angular2.dev.js:9665) 
    at AbstractChangeDetector.runDetectChanges (angular2.dev.js:9593) 

的dashboard.component:

import { Component, OnInit } from 'angular2/core'; 
import { Router } from 'angular2/router'; 
import { Category } from '../model/category'; 
import { CategoryService } from '../service/category.service'; 

@Component({ 
    selector: 'my-dashboard', 
    templateUrl: 'app/view/dashboard.component.html', 
    styleUrls: ['app/view/dashboard.component.css'] 
}) 
export class DashboardComponent implements OnInit { 
    categories: Category[] = []; 
    constructor(private _router: Router, private _categoryService: CategoryService) { } 
    ngOnInit() { 
    this._categoryService.getCategories().subscribe(
      data => { this.categories = data }, 
      err => console.error(err) 
    ); 
    } 
    gotoDetail(category: Category){ 
     let link = ['CategoryDetail', { id: category.id }]; 
     this._router.navigate(link); 
    } 
} 

我使用的是最新版本:

{ 
    "name": "angular2quickstart", 
    "version": "1.0.0", 
    "scripts": { 
    "postinstall": "npm run typings install", 
    "tsc": "tsc", 
    "tsc:w": "tsc -w", 
    "lite": "lite-server", 
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ", 
    "typings" : "typings" 
}, 
    "license": "ISC", 
"dependencies": { 
    "angular2": "2.0.0-beta.13", 
    "systemjs": "0.19.25", 
    "es6-promise": "^3.0.2", 
    "es6-shim": "^0.35.0", 
    "reflect-metadata": "0.1.3", 
    "rxjs": "5.0.0-beta.4", 
    "zone.js": "0.6.9" 
}, 
"devDependencies": { 
    "concurrently": "^2.0.0", 
    "lite-server": "^2.0.1", 
    "typescript": "^1.7.5", 
    "typings": "^0.7.12" 
    } 
} 
+0

歡迎來到StackOverflow。請提供允許重現問題的必要信息。你如何使用鏈接的代碼? –

回答

0

不能使用useClass時你可以這樣定義關聯的提供者,但是useFactory

bootstrap(AppComponent, [ 
    HTTP_PROVIDERS, 
    provide(Http, { 
    useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), 
    deps: [XHRBackend, RequestOptions] 
    }) 
]); 

這樣你將提供後端注入。

編輯

我發現有一個問題你定義類的方式。你應該嘗試這樣的事情:

export class CustomHttp extends Http { 
    (...) 
} 

並註冊它與provide函數如上所述。

+0

我更新了我的問題。我會嘗試這種方法。但實際上我懷疑我的進口有問題,因爲我的代碼與樣品幾乎相同。 – user2038560

+0

我認爲問題在於你如何定義你的班級(使用'NgHttp')... –

+0

我更新了我的答案。使用類似的東西:'export class CustomHttp extends Http {...' –