简体   繁体   English

Angular2 http订阅组件

[英]Angular2 http subscribe component

An angular2 app, try to register an email. 一个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')
        });
    }
}

my ApiService is simple: 我的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())
    }

}

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

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 . 那是因为你在TypeScript使用了function关键字。 Never do this. 永远不要这样做。 Always use the arrow notation () => {} . 始终使用箭头符号() => {}

You should change your next function to: 您应该将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.

相关问题 Angular Http 订阅 - 无法分配给组件中的变量 - Angular Http subscribe - cannot assign to variable in component 角度2-可以在“呼叫”组件中订阅http错误吗? - Angular 2 - Possible to subscribe to http errors in the 'calling' component? 使用Observable的Angular2 HTTP订阅显示未定义的数据 - Angular2 HTTP using observables subscribe showing data undefined 分配Angular2中Http订阅方法返回的值 - Assign value returned by Http subscribe method in Angular2 Angular2地图并订阅 - Angular2 map and subscribe Angular2-如何在组件中链接异步服务调用(http请求)? - Angular2 - How to chain async service calls (http requests) in a component? Angular2 / TypeScript和HTTP:如何将对象附加到组件? - Angular2/TypeScript & HTTP: How to attach object to component? Angular2 http.get(),map(),subscribe()和可观察模式 - 基本理解 - Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding angular 5+ 相同的路由,相同的组件但不同的参数,不在 angular 订阅上发送 http get 请求 - angular 5+ same routing, same component but different param, not send http get request on angular subscribe Angular 2-无法将http subscription()方法的返回值分配给组件内部的全局变量 - Angular 2 - Unable to assign return value from http subscribe() method to a global variable inside component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM