嗨,我是前台开发人员,所以我不知道后端的代码。
现在,我正在使用POST请求从服务器获取用户信息,并且我已成功获取json对象中的用户数据(至少我认为)但由于某些原因,我无法使用此json数据。 / p>
也许我收到的数据不正确,或者我忘了添加一些代码,但我不知道如何解决这个问题。
这些是代码。
模型
export interface User {
birthday: number;
email:string;
gender:string;
memberType: string;
name: string;
phone: string;
profilePicture: string;
uid:string;
}
登录服务
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import { RequestMethod, RequestOptions, URLSearchParams } from '@angular/http';
import { Router } from '@angular/router';
import { User } from '../../model/auth_user';
import { environment } from '../../index/baseUrl';
@Injectable()
export class AuthenticationService {
constructor(private http: Http, private router: Router) { }
login(email: string, password: string) {
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'post');
headers.append('Access-Control-Allow-Origin', '*');
headers.append("X-Requested-With", "XMLHttpRequest");
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('email', email);
body.set('password', password);
return this.http.post(`${environment.baseurl}` + '/api/member/login', body, options)
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
登录组件
export class LoginPageComponent implements OnInit {
constructor(private location: Location,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService) {
}
model: any = {};
loading = false;
returnUrl: string;
error = '';
ngOnInit() {
// reset login status
this.authenticationService.logout();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['main'] || '/';
}
login() {
this.loading = true;
this.authenticationService.login(this.model.email, this.model.password)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.error = "Wrong Id or Password"; <- this doesn't appear even though the error spits 404 I don't know why.. :(
this.loading = false;
});
}
backClicked() {
this.location.back();
}
}
登录html模板
<form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
<div id="main-container">
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !email.valid }">
<label for="email">email</label>
<input type="text" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel" required />
<div *ngIf="f.submitted && !email.valid" class="help-block">Please type in your e-mail</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
<label for="password">Password</label>
<input type="password" class="form-control" name="password"
[(ngModel)]="model.password" #password="ngModel" required />
<div *ngIf="f.submitted && !password.valid" class="help-block">Please type in password.</div>
<br>
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary" id="button3">Login</button>
<img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
</div>
<div *ngIf="error" class="alert alert-danger">{{error}}</div>
</div>
</form>
在这里,我还想要用户输入错误的id或pw,如果服务器吐出404错误,我想显示错误的id或密码,但我的方法不起作用。
主页组件
export class MainComponent {
public toggled(open: boolean): void {
console.log('Dropdown is now: ', open);
}
onClick() {
}
currentUser: User;
items: Object[] = [];
constructor(private authguard: AuthGuard) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
}
现在我想得到currentUser的名字和memberType,但它不起作用! 主页组件html模板
<p class="drpdown3" role="menuitem"> Welcome! {{currentUser.name}}{{currentUser.memberType | type_transform}}</p>
这不起作用..
我做错了什么?
我指的是这个网站:http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial