我正在从我的身份验证服务中调用一个方法,该方法返回用户名和密码是否正确,也是一个身份验证令牌。当我通过调用getAuthData方法获取数据后尝试打印值时,它会输出authData.status的默认值/无效值 - false。
但是,通过执行{{authData.status}}从我的模板视图打印值,它会在提交表单后显示正确的值。我已经尝试使用谷歌搜索,浏览文档,但到目前为止没有运气。我是应该订阅服务更改还是我缺少什么?
问题显示在authSubmit()方法@ admin.component.ts
中admin.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AdminComponent } from './admin.component';
import { AuthService } from '../shared/auth/index';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [AdminComponent],
exports: [AdminComponent],
providers: [AuthService]
})
export class AdminModule { }
auth.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
export class AuthData {
public status: boolean;
public token: string;
public constructor(initStatus: boolean = false, initToken: string = '') {
this.status = initStatus;
this.token = initToken;
}
}
@Injectable()
export class AuthService {
public authData: AuthData;
public constructor(public http: Http) {
this.authData = new AuthData();
}
public getAuthData(user: string, pass: string): Observable<AuthData> {
return this.http.get('http://api.dev/auth?user=' + user+ '&pass=' + pass)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Error'));
}
}
admin.component.ts
import { Component } from '@angular/core';
import { AuthService, AuthData } from '../shared/index';
@Component({
moduleId: module.id,
selector: 'my-admin',
templateUrl: 'admin.component.html',
styleUrls: ['admin.component.css']
})
export class AdminComponent {
public authUser: string;
public authPass: string;
public authData: AuthData;
public constructor(public authService: AuthService) {
this.authData = this.authService.authData;
}
public authSubmit(): boolean {
this.authService.getAuthData(this.authUser, this.authPass)
.subscribe(
data => this.authData = data,
err => console.log(err)
);
// alert result: authData.status = false | should be: true
alert('authData.status= ' + authdata.status);
return false;
}
}
admin.component.html
<form *ngIf="!authData.status" (submit)="authSubmit()">
<input [(ngModel)]="authUser" type="text">
<input [(ngModel)]="authPass" type="password">
<button type="submit">Sign In</button>
</form>
authData.status = {{authData.status}}
答案 0 :(得分:0)
解决了,这样一个愚蠢的错误和简单的解决方案。
public authSubmit(): boolean {
let authStatus: boolean = false;
this.authService.getAuthData(this.authUser, this.authPass)
.subscribe(
data => {
this.authService.authData = data;
authStatus = data.status;
},
err => console.log(err)
);
alert('authStatus = ' + authStatus);
return false;
}