1

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: '[email protected]',
            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

1 Answer 1

0

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)
   }
Sign up to request clarification or add additional context in comments.

2 Comments

wtf... i really appreciate for that. i crazy for it one day!!! thank u twice!!! i want to use angular2 at a production environment.
If you are happy, i am happy ;). Welcome to the world of typescript and angular2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.