我是角色2的新手。我在登录的响应中调用了getSession()方法,但它仍然给了我未经授权的用户错误,我不明白这个错误背后的原因是什么。这是我的代码 login.ts 是组件, user-service.ts 是我在login.ts中调用的服务来获取会话。
login.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HomePage } from '../home/home';
import { SignupPage } from '../signup/signup';
import { UserServiceProvider } from '../../providers/user-service/user-service';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loginForm: FormGroup;
invalidCredentials;
signupPage = SignupPage;
user = { username: "", password: "" };
constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, private userService: UserServiceProvider) {
this.loginForm = formBuilder.group({
emailAddress: ['', Validators.compose([Validators.email, Validators.required])],
password: ['', Validators.compose([Validators.minLength(4), Validators.required])]
});
}
loginUser() {
this.userService.login(this.user.username, this.user.password)
.subscribe(data => {
this.getSession();
this.invalidCredentials = false;
this.navCtrl.setRoot(HomePage)
}, err => {
this.invalidCredentials = true;
}
);
}
getSession() {
this.userService.getSessionFromServer().subscribe(data=> {
console.log("getsesion");
},err=>{
console.log("err");
});
}
}
用户-service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, Request, RequestMethod } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { NavController, NavParams } from 'ionic-angular';
import { SettingServiceProvider } from '../../providers/setting-service/setting-service';
import { LoginPage } from '../../pages/login/login';
@Injectable()
export class UserServiceProvider {
session: any;
constructor(public http: Http, private settingServiceProvider: SettingServiceProvider ) {
}
login(username: string, password: string): any {
var creds = "username=" + username + "&password=" + password;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(this.settingServiceProvider.setting().baseUrl + 'login', creds,
{ headers: headers }
);
}
getSessionFromServer(){
return this.http.get(this.settingServiceProvider.setting().baseUrl + "session")
.map((res:Response) => res.json());
}
}
提前谢谢