Angular2 Http请求

时间:2015-08-19 13:29:50

标签: javascript angular typescript angular2-http

您好我正在尝试使用<Viewbox Width="16" Height="16" Child="{StaticResource mPencilCanvas}"/> 中的HTTP模块发送获取请求。

Angular2(1.5)中的所有内容都很好,但Typescript在控制台中显示以下错误:

Chrome

Services.ts

EXCEPTION: Error during instantiation of EntryList!. ORIGINAL
EXCEPTION: TypeError: Cannot read property 'merge' of undefined
ORIGINAL STACKTRACE: TypeError: Cannot read property 'merge' of undefined
at mergeOptions (angular2.dev.js:27991)  
at execute.Http.get (angular2.dev.js:28052)  
at EntryService.getEntries (services.js:17)
at new EntryList (entry-list.js:20)

入门list.ts

/// <reference path="../typings/angular2/angular2.d.ts" />
import { Http, Observable } from "angular2/angular2"

export class EntryService {
    private _entries: Array<string>;
    private _http : Http;

    constructor() {     
        this._entries = ["test1", "test2", "test3"];
        this._http = new Http;      
    }

    get Entries() : Array<string> {
        return this._entries;
    }

    getEntries()
    {
        console.log(this._http);
        return this._http.get('http://localhost:53338/api/decisions')       
            .toRx()
            .map((response) => { 
                response.json()
            });     
    }
}

app.ts

/// <reference path="../typings/angular2/angular2.d.ts" />
/// <reference path="../modules/services.ts" />

import { Component, View, NgFor } from "angular2/angular2"
import { EntryService } from "modules/services"

@Component({
    selector: 'entry-list'  
})
@View({
    directives: [ NgFor ],
    templateUrl: "../views/entry-list.html" 
})
export class EntryList {
    entries: Array<string>; 

    constructor(public service: EntryService) {     
        this.entries = this.service.Entries;
        this.service.getEntries().subscribe((response) => {     
            console.log(response);
        }); 
    }
}

的index.html

/// <reference path="typings/angular2/angular2.d.ts" />
/// <reference path="components/entry-list.ts" />
/// <reference path="modules/services.ts" />

import { Component, View, bootstrap, NgFor } from "angular2/angular2"
import { EntryList } from "components/entry-list"
import { EntryService } from "modules/services"

@Component({
    selector : "app",
    bindings: [ EntryService ]  
})
@View({
    directives: [ EntryList ],
    templateUrl: "views/app.html"   
})
class App { 
    constructor() {
        console.log('hit');
    }
}

bootstrap(App);

我确实查看了<html> <head> <title>SCM</title> <script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.88/traceur-runtime.js"></script> <script src="https://jspm.io/system@0.16.js"></script> <script src="https://code.angularjs.org/2.0.0-alpha.34/angular2.dev.js"></script> </head> <body> <app></app> <script>System.import('app')</script> </body> </html> 网站上的API文档,但看不出什么错误。

更新

Services.ts

angular.io

入门list.ts

/// <reference path="../typings/angular2/angular2.d.ts" />
import { Http, Observable, httpInjectables } from "angular2/angular2"

export class EntryService {
    private _entries: Array<string>;    

    constructor(private http: Http) {       
        this._entries = ["test1", "test2", "test3"];            
    }

    get Entries() : Array<string> {
        return this._entries;
    }

    getEntries()
    {
        console.log(this.http);
        return this.http.get('http://localhost:53338/api/decisions')        
            .toRx()
            .map((response) => { 
                response.json()
            });     
    }
}

app.ts

/// <reference path="../typings/angular2/angular2.d.ts" />
/// <reference path="../modules/services.ts" />

import { Component, View, NgFor, Http, httpInjectables } from "angular2/angular2"
import { EntryService } from "modules/services"

@Component({
    selector: 'entry-list',
    bindings : [ Http, httpInjectables ]
})
@View({
    directives: [ NgFor ],
    templateUrl: "../views/entry-list.html" 
})
export class EntryList {
    entries: Array<string>; 

    constructor(public service: EntryService) {     
        this.entries = this.service.Entries;
        this.service.getEntries().subscribe((response) => {     
            console.log(response);
        }); 
    }
}

/// <reference path="typings/angular2/angular2.d.ts" /> /// <reference path="components/entry-list.ts" /> /// <reference path="modules/services.ts" /> import { Component, View, bootstrap, NgFor, Http, httpInjectables } from "angular2/angular2" import { EntryList } from "components/entry-list" import { EntryService } from "modules/services" @Component({ selector : "app", bindings: [ EntryService, Http, httpInjectables ] }) @View({ directives: [ EntryList ], templateUrl: "views/app.html" }) class App { constructor() { console.log('hit'); } } bootstrap(App);

没有任何更改

编辑:我的services.ts文件已更改以使其正常工作:

index.html

2 个答案:

答案 0 :(得分:10)

你不应该自己实例化Http,而是注入它:

public constructor(http : Http) {
    this.http = http;
}

文档说:

  

Http作为可注入类提供,具有执行http请求的方法。

因此,如果您自己实例化,我不确定结果是什么,但由于某些内部未定义,它无法以某种方式设法执行get请求。

编辑:添加更多来源。

@Injectable()
export class Http {
    constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {}

    /**
     * Performs a request with `get` http method.
     */
    get(url: string, options?: RequestOptionsArgs): EventEmitter {
        return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options, RequestMethods.GET, url)));
  }
}

这里我从github repo中添加了一小部分Http类。你可以看到_backend和_defaultOptions是在你没有给出的构造函数中给出的,方法get()将根据options参数和构造函数中给出的_defaultOptions构建请求的选项,因为你没有提供其中,我相信它会在你可以在这里找到的mergeOptions调用中崩溃:

function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
  var newOptions = defaultOpts;
  if (isPresent(providedOpts)) {
    // Hack so Dart can used named parameters
    newOptions = newOptions.merge(new RequestOptions({
      method: providedOpts.method,
      url: providedOpts.url,
      search: providedOpts.search,
      headers: providedOpts.headers,
      body: providedOpts.body,
      mode: providedOpts.mode,
      credentials: providedOpts.credentials,
      cache: providedOpts.cache
    }));
  }
  if (isPresent(method)) {
    return newOptions.merge(new RequestOptions({method: method, url: url}));
  } else {
    return newOptions.merge(new RequestOptions({url: url}));
  }
}

在函数的最后一个if / else处。有关更多信息,源文件位于here

答案 1 :(得分:2)

你真的想为CRUD / HTTP请求使用另一个库吗? **

  

我强烈推荐es6 de-facto fetch。它不仅是   我认为现在比angular2 / http更简单,但也是   标准现在和将来的版本。

**它开箱即用于safari,chrome,ie-edge和firefox。