简体   繁体   中英

Angular2 http subscribe component

An angular2 app, try to register an email.

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')
        });
    }
}

my ApiService is simple:

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())
    }

}

this is my 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>

I can success send the api to server and received response, I subscribe an observer to the http response which is a Observable object, inner the next function, I console.log() my successMessage , but i got 'undefined', and when I change the successMessage my html has no change.

It seems like I have lost the scope of my component, then I can't use this keyword

That's because you use the function keyword inside TypeScript . Never do this. Always use the arrow notation () => {} .

You should change your next function to:

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)
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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