Angular JS 2 HTTP Post:对象不支持属性或方法' toPromise'

时间:2016-04-17 07:30:06

标签: typescript angular

这让我感到困惑。我试图通过拼凑各种示例来组装基于AngularJS 2的简单注册页面。完成this我已经接近向我的服务器方向发送一些数据,但是我收到了:

Object doesn't support property or method 'toPromise'
   at RegisterService.prototype.registerUser (eval code:22:9)
   at RegisterFormComponent.prototype.submit (eval code:24:9)
   at ChangeDetector_RegisterFormComponent_0.prototype.handleEventInternal (Function code:600:1)
   at AbstractChangeDetector.prototype.handleEvent (http://localhost:53078/register.html:8036:9)
   at AppView.prototype.triggerEventHandlers (http://localhost:53078/register.html:10736:7)
   at Anonymous function (Function code:753:118)
   at Anonymous function (http://localhost:53078/register.html:13905:7)
   at Anonymous function (http://localhost:53078/register.html:13254:11)
   at Zone.prototype.run (http://localhost:53078/libs/angular2-polyfills.js:1243:14)
   at Anonymous function (http://localhost:53078/register.html:13456:15)

我相信我的代码中的适用行是这一行:

return this.http.post(this._registerUrl, body, options)
    .toPromise()
    .then(this.extractData)
    .catch(this.handleError);

我试图构建一个promise base系统,但如果我尝试使用基于observables的系统,我会收到类似的信息:

Object doesn't support property or method 'map'
   at RegisterService.prototype.registerUser (eval code:24:9)
   at RegisterFormComponent.prototype.submit (eval code:24:9)
   at ChangeDetector_RegisterFormComponent_0.prototype.handleEventInternal (Function code:600:1)
   at AbstractChangeDetector.prototype.handleEvent (http://localhost:53078/libs/angular2.dev.js:8036:9)
   at AppView.prototype.triggerEventHandlers (http://localhost:53078/libs/angular2.dev.js:10736:7)
   at Anonymous function (Function code:753:118)
   at Anonymous function (http://localhost:53078/libs/angular2.dev.js:13905:7)
   at Anonymous function (http://localhost:53078/libs/angular2.dev.js:13254:11)
   at Zone.prototype.run (http://localhost:53078/libs/angular2-polyfills.js:1243:14)
   at Anonymous function (http://localhost:53078/libs/angular2.dev.js:13456:15)

我的基于承诺的应用程序的源代码如下。

Register.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Angular 2 with ASP.NET 5</title>

    <!-- Load library bits and pieces -->
    <link href="/libs/css/bootstrap.css" rel="stylesheet" />
    <script src="/libs/es6-shim.min.js"></script>
    <script src="/libs/system-polyfills.js"></script>
    <script src="/libs/shims_for_IE.js"></script>
    <script src="/libs/angular2-polyfills.js"></script>
    <script src="/libs/system.js"></script>
    <script src="/libs/rx.js"></script>
    <script src="/libs/angular2.dev.js"></script>
    <script src="libs/http.dev.js"></script>

    <!-- Load our bits and pieces -->
    <link href="/styles/forms.css" rel="stylesheet" />

    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                scripts: {
                    defaultExtension: 'js'
                }
            }
        });
    </script>
    <script>

        System.import('scripts/register-boot.js')
              .then(null, console.error.bind(console));
    </script>
</head>
<body>
    <h2>Let's Get Started!</h2>
    <register-form>Loading...</register-form>
</body>
</html>

寄存器form.component.html

<div class="container">
    <h2>Details</h2>
    <form>
        <div class="form-group">
            <label for="phoneNumber">Phone Number</label>
            <input type="text" class="form-control" required
                    [(ngModel)]="request.phoneNumber" 
                    ngControl="phoneNumber" #phoneNumber="ngForm">
            <div [hidden]="phoneNumber.valid || phoneNumber.pristine"
                class="alert alert-danger">
                Phone number is required.
            </div>
        </div>

        <div class="form-group">
            <label for="pinNumber">Pin Number</label>
            <input type="text" class="form-control" required
                   [(ngModel)]="request.pinNumber"
                   ngControl="pinNumber" #pinNumber="ngForm">
            <div [hidden]="pinNumber.valid || pinNumber.pristine"
                 class="alert alert-danger">
                Pin number is required.
            </div>
        </div>
        <button type="submit" class="btn btn-default" (click)="submit();">Register</button>
    </form>
</div>

寄存器boot.ts

///<reference path="../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser'
import {RegisterFormComponent} from './register-form.component'
bootstrap(RegisterFormComponent);

寄存器form.component.ts

import {Component} from 'angular2/core';
import {NgForm} from 'angular2/common';
import { HTTP_PROVIDERS } from 'angular2/http';
import { RegisterRequest } from './register-request'
import { RegisterService } from './register-service'

// directives: [HeroFormComponent] Should I add this?
@Component({
    selector: 'register-form',
    templateUrl: 'fragments/register-form.component.html',
    providers:  [
        HTTP_PROVIDERS,
        RegisterService,
    ]

})

export class RegisterFormComponent {

    constructor(private _registerService: RegisterService) { }

    request = new RegisterRequest("", "");
    errorMessage: string;

    submit() {
        // if (!model) { return; }
        this._registerService.registerUser(this.request.phoneNumber,
                this.request.pinNumber)
            .then(result => null,
            error => this.errorMessage = <any>error);
    }
}

寄存器request.ts

import {Component} from 'angular2/core';

export class RegisterRequest {
    constructor(public phoneNumber: string,
        public pinNumber: string) {
    }
}

寄存器service.ts

import {Injectable}     from 'angular2/core';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class RegisterService {
    constructor (private http: Http) {}

    private _registerUrl = '/api/account/register';

    registerUser(phoneNumber: string, pinNumber: string): Promise<string> {

        let body = JSON.stringify({ phoneNumber, pinNumber });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this._registerUrl, body, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        if (res.status < 200 || res.status >= 300) {
            throw new Error('Bad response status: ' + res.status);
        }
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: any) {
        let errMsg = error.message || 'Server error';
        return Promise.reject(errMsg);
   }
}

2 个答案:

答案 0 :(得分:3)

绝对是

import 'rxjs/Rx';

当我无法在Http中获取地图方法时,遗漏了什么。我现在可以从服务器检索数据。

遗憾的是,这并没有更好的记录。

百万感谢!

答案 1 :(得分:1)

找到它。这样:

<强>寄存器boot.ts

///<reference path="../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser'
import {RegisterFormComponent} from './register-form.component'
bootstrap(RegisterFormComponent);

应该是这样的:

///<reference path="../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser'
import 'rxjs/Rx';
import {RegisterFormComponent} from './register-form.component'
bootstrap(RegisterFormComponent);

请注意额外的导入。