如何在传播中使用observables
我是Angular的新手。我正在尝试授权并面临以下任务:如何在传播中使用observables
有一种服务从前端获取用户。我想将此用户存储在服务中。为此,我使用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);
});
}
}
回答:
可能是值得约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);
}
}
无需更换组件。
以上是 如何在传播中使用observables 的全部内容, 来源链接: utcz.com/qa/264801.html