我在使用.subscribe函数时遇到了问题。首先,我有一个函数向服务器发送请求。
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());
}
现在,user.service将sendRequest委托给此文件,我已经在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;
}
现在我想在componentLogin中获取serverReturn,因此我必须根据调用的响应知道该做什么。 但是.subscribe的回调似乎无法访问此类的属性。 我正在遵循这个 答案。 我从那里学到:
通常,您会将成功回调的结果分配给您的变量。
最后,这是我的登录组件,它调用用户服务中的登录功能。
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');
}
}
问题在于,无论我尝试在成功回调函数中进行任何变量或更改,我都会收到未定义的返回值。如果我从订阅中调用任何方法,也会出现错误。 例如,如果我尝试这样做。
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
我哪里做错了?我试图将结果设置为一个类变量。为什么我在subscribe回调函数中调用的所有内容似乎都是未定义的? 非常感谢您的帮助。谢谢。
this
值。尝试使用lambda,即data => this.modal.showmodal('登录','登录')
。 - Jason Goemaatdata => this.result = data
设置变量,仍然会在控制台中得到未定义的结果。为什么? - David Valewindow ['mythis'] = this; console.log(this);
尝试在订阅之前在函数中设置一个本地变量,并记录该变量(或使用它),例如:var self = this;
然后在回调中self.result = data;
- Jason GoemaatuserService.login
的方式。你能否给出一个更清晰的例子,说明你想做但无法做到的事情? - Jason Goemaat