我是Angular的新手。我正在尝试授权并面临以下任务:
有一项服务可以从前端获取用户。我想将此用户存储在服务本身中。为此,我使用checkUser()
函数。接下来,从组件,我想访问此变量,当它在服务中更改时,组件接收到这些更改。我认为我可以在服务中使用Observable
(getCurrentUser()
函数)。但该组件没有提出任何建议。你能告诉我什么是错的以及我如何实现这个?谢谢你的建议。
const API_URL = environment.apiUrl;
@Injectable()
export class AuthService {
// public user: Account;
public user: Account;
constructor(private http: HttpClient) {
this.checkUser();
const intervalId = setInterval(() => {
console.log('Auth: ', this.user);
}, 2000);
}
checkUser() {
return this.http
.get<Account>(API_URL + '/get_user', { withCredentials: true })
.take(1)
.subscribe(user => {
this.user = user;
console.log(this.user);
});
}
login(user) {
this.http
.post<Account>(API_URL + '/login', user, { withCredentials: true
}).take(1)
// .catch(this.handleError)
.subscribe(response => {
console.log('Resp: ', response);
this.checkUser();
});
}
getCurrentUser(): Observable<Account> {
return Observable.of(this.user);
}
private handleError(error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}
}
@Component({
selector: 'app-bs-navbar',
templateUrl: './bs-navbar.component.html',
styleUrls: ['./bs-navbar.component.css']
})
export class BsNavbarComponent implements OnInit {
// public user$: Observable<Account>;
public user: Account;
constructor(private authService: AuthService) {
const intervalId = setInterval(() => {
console.log(this.user);
}, 2000);
}
ngOnInit() {
this.authService.getCurrentUser().
subscribe(user => {
this.user = user;
console.log('Navbar: ', user);
});
}
}
答案 0 :(得分:1)
关于Subject
可能值得关注吗?
服务代码:
const API_URL = environment.apiUrl;
@Injectable()
export class AuthService {
private user: Subject<Account> = new Subject();
constructor(private http: HttpClient) {
this.checkUser();
}
checkUser() {
return this.http
.get<Account>(API_URL + '/get_user', { withCredentials: true })
.take(1)
.subscribe(user => {
this.user.next(user);
});
}
login(user) {
this.http
.post<Account>(API_URL + '/login', user, { withCredentials: true })
.take(1)
.subscribe(response => {
this.checkUser();
});
}
getCurrentUser(): Observable {
return this.user.asObservable();
}
private handleError(error: Response | any) {
return Observable.throw(error);
}
}
无需更改组件。