繁体   English   中英

Angular2 http订阅组件

[英]Angular2 http subscribe component

一个angular2应用程序,尝试注册一个电子邮件。

import {Component, Directive, provide, Host} from '@angular/core';
import {NG_VALIDATORS, NgForm} from '@angular/forms';
import {ChangeDetectorRef, ChangeDetectionStrategy} from '@angular/core'; 
import {ApiService} from '../../services/api.service';

import {actions} from '../../common/actions';
import {EmailValidator} from '../../directives/email-validater.directive';
import * as _ from 'lodash';
import * as Rx from 'rxjs';

@Component({
    selector: 'register-step1',
    directives: [EmailValidator],
    styleUrls: ['app/components/register-step1/register.step1.css'],
    templateUrl: 'app/components/register-step1/register.step1.html'
})
export class RegisterStep1 {

    email: string;
    userType: number;
    errorMessage: string;
    successMessage: string;

    constructor(private _api: ApiService, private ref: ChangeDetectorRef) {
    this.successMessage = 'success';
    this.errorMessage = 'error';

    }

    submit() {

        var params = {
            email: this.email,
            type: +this.userType
        };
        params = {
            email: '1@qq.com',
            type: 3
        };

        this._api.query(actions.register_email, params).subscribe({
            next: function(data) {
                if(data.status) {
                    console.log("success register");
                    this.successMessage = "ok ,success";
                    console.log(this.errorMessage, this.successMessage);    
                }else{
                    this.errorMessage = data.message;
                    console.warn(data.message)
                }
            },
            error: err => console.log(err),
            complete: () => console.log('done')
        });
    }
}

我的ApiService很简单:

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import {AjaxCreationMethod, AjaxObservable} from 'rxjs/observable/dom/AjaxObservable';

import {logError} from '../services/log.service';
import {AuthHttp, AuthConfig, AUTH_PROVIDERS} from 'angular2-jwt';

@Injectable()
export class ApiService {
    _jwt_token:string;

    constructor(private http:Http) {

    }


    toParams(paramObj) {
        let arr = [];
        for(var key in paramObj) {
            arr.push(key + '=' + paramObj[key]);
        }
        return arr.join('&')
    }

    query(url:string, paramObj:any) {
        let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(url, this.toParams(paramObj), options).map(res=>res.json())
    }

}

这是我的HTML:

<form #f="ngForm">
usertype<input type="text" name="userType" [(ngModel)]="userType"><br/>
    <input type="text" name="email" ngControl="email" email-input required [(ngModel)]="email">
    <button [disabled]="!f.form.valid" (click)="submit(f.email, f.userType)">add</button>

</form>
{{f.form.errors}}
<span *ngIf="errorMessage">error message: {{errorMessage}}</span>
<span *ngIf="successMessage">success message: {{successMessage}}</span>

我可以成功将api发送到服务器并收到响应,我订阅了一个观察者到http响应,这是一个Observable对象,内部是下一个函数,我console.log()我的successMessage ,但是我得到'undefined',当我更改successMessage我的html没有变化。

好像我已经失去了我的组件的范围,然后我不能使用这个关键字

那是因为你在TypeScript使用了function关键字。 永远不要这样做。 始终使用箭头符号() => {}

您应该将next功能更改为:

next: (data) => {
   if(data.status) {
        console.log("success register");
        this.successMessage = "ok ,success";
        console.log(this.errorMessage, this.successMessage);    
   }else{
        this.errorMessage = data.message;
        console.warn(data.message)
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM