简体   繁体   English

Angular 2 Http Observable订阅回调函数

[英]Angular 2 Http Observable subscribe callback function

I have an problem with the .subscribe function. 我的.subscribe功能有问题。 First I have an function to send a request to the server. 首先,我有一个向服务器发送请求的功能。 That's it. 而已。

protected sendRequest(data:string,url:string):Observable<any>{

    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({ headers: headers });

    //let body = 'email=' + 'email' + '&password=' + 'password';
    return this.http.post(url, data, options).map(response => response.json());
}

Now the user.service delegates the sendResquest to this file, I have injected the server.service in the user.service and so on. 现在user.service将sendResquest委托给这个文件,我已经在user.service中注入了server.service,依此类推。

public login(email:string, password:string):Observable<any>{
    //format data to send
    let data:string = 'email=' + email + '&password=' + password;
    //let body = 'email=' + 'email' + '&password=' + 'password';

    let serverReturn:Observable<any> = this.sendRequest(data,"server/request/signin.php");
    //Log the server return
    //console.log(serverReturn);

    serverReturn.subscribe(
        //set the token and session elements of a logged user
        function(data){
            //console.log(data);
            //console.log(data.isSigned);
            if(data.isSigned == "true"){
                sessionStorage.setItem("isSigned","true");
                sessionStorage.setItem("userToken", data.userToken);
            } else if(data.userBlocked == "true"){
                sessionStorage.setItem("isSigned", "false");
            } else {
                sessionStorage.setItem("isSigned", "false");
            }
        }
    );
    return serverReturn;
}

Now what I whant is get this serverReturn in the componentLogin, so there I have to know what to do based on the response for this calling. 现在我想要的是将此服务器返回到componentLogin中,因此我必须根据此调用的响应知道该怎么做。 But the callback from .subscribe seems not to have access to the properties of this class. 但是来自.subscribe的回调似乎无法访问此类的属性。 I'm following this answer There I learned that: 我正在按照这个答案在那里我了解到:

Usually, you take the results from the success callback and assign it to your variable. 通常,您从成功回调中获取结果并将其分配给您的变量。

Finally this is my login component witch call the login from user.service 最后这是我的登录组件,从user.service调用登录

import { Component, ElementRef, ViewChild } from '@angular/core';
import { ModalComponent } from '../../ui/modal/modal.component';

import { UserService } from '../../utils/user.service';

@Component({
selector: 'login',
templateUrl: 'app/system/login/tpl.html',
styleUrls: ['app/system/login/style.css'],
directives: [ModalComponent],
providers: [UserService]
})
export class LoginComponent {
constructor(private userService:UserService, private elementRef:ElementRef){

}
private result:Array<any>;
@ViewChild(ModalComponent) modal:ModalComponent;
private signin():void{

    let email:string =  this.elementRef.nativeElement.querySelector("#email").value;
    let password:string = this.elementRef.nativeElement.querySelector("#password").value;

    this.userService.login(email, password).subscribe(data => this.result = data);
    console.log(this.result);

    //this.modal.showModal('Login ','Login');
}
}

The problem is that any variable or change that I try to do within the success callback I get an undefined return. 问题是我尝试在成功回调中做的任何变量或更改都会得到一个未定义的返回。 If I call a method, any method from the subscribe this get me an error too. 如果我调用一个方法,订阅中的任何方法都会给我带来错误。 For example, if I try to do this. 例如,如果我尝试这样做。

this.userService.login(email, password).subscribe(
        function(data){
            this.modal.showModal('Login ','Login');
        }
    );

I get an error: 我收到一个错误:

EXCEPTION: TypeError: Cannot read property 'showModal' of undefined

What I get wrong? 我错了什么? I'll try to set the result to an class variable. 我将尝试将结果设置为类变量。 Why that all I call within the subscribe callback function seems to be undefined? 为什么我在subscribe回调函数中调用的所有内容似乎都未定义? I'll appreciate any help on this. 我会感谢任何帮助。 Thanks. 谢谢。

As Jason Goemaat already mentioned, you need to use lambdas to access class properties. 正如Jason Goemaat已经提到的,你需要使用lambdas来访问类属性。

The reason why you won't see them in the debugger is that in the transpiled code this is assigned to _this . 为什么你不会看到他们在调试器的原因是,在transpiled代码this被分配到_this You will see a line 你会看到一条线

var _this = this;

and for the rest of the lambda _this is used. 对于lambda的其余部分_this被使用。 That's why the debugger doesn't know any this. 这就是调试器不知道this. variables inside lambdas. lambda中的变量。

Try WebStorm for example. 以WebStorm为例。 That IDE comes with a debugger that is aware of that issue and compensates for it automatically. 该IDE附带一个调试器,它可以识别该问题并自动进行补偿。 However, it works with chrome only, as it is dependent on a chrome add-on. 但是,它仅适用于chrome,因为它依赖于chrome附加组件。

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

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