我正在Angular 5中构建一个应用程序,并试图使用我的服务“ user_logged_in”创建一个全局变量。它可以正常工作,就像我可以从其他组件访问它一样,但是一旦更新了变量,如何使该组件重新读取变量呢?
因此,如果用户成功登录,则将变量更改为true。那部分起作用。但是,我还有另一个组件(已经渲染过),仅当用户登录时才需要数据。如何使它不断侦听更改并重新评估布尔值,一旦正确就重新加载数据?>
我的服务如下:
import { Injectable, OnInit } from '@angular/core';
import { Subject, Observable } from "rxjs";
import 'rxjs/add/operator/map';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
@Injectable()
export class AuthService {
user_logged_in: Boolean;
}
constructor(public authService: Http, private router: Router) {}
logInUser(signInData: { username: string, password: string }): Observable<Response> {
return this.authService.post('api.url', signInData)
.map(res => {
var data = res.json()
if (data.status = 200){
this.user_logged_in = true
}
return res
}
)
}
该组件看起来像:
import { Component, Inject, OnInit, Input, AfterViewInit } from '@angular/core';
import { DataService } from '../data.service';
import { HttpClient } from '@angular/common/http';
import { AuthService } from "../services/auth.service";
@Component({
selector: 'app-sitelist',
templateUrl: './sitelist.component.html',
styleUrls: ['./sitelist.component.css']
})
export class SitelistComponent implements OnInit {
data_returned: boolean;
logged_in: Boolean;
constructor(public data: DataService, private http: HttpClient, private _dataService: DataService, public authService: AuthService) {
}
ngOnInit() {
this.data_returned = false;
//only load data if the global variable is true
if (this.authService.user_logged_in == true) {
this.authService.getSites()
.subscribe(data => {
this.data_returned = true;
this.sites = data;
this.authService.all_sites = data;
})
}
}
}
因此,如果我的组件已经加载并且在用户登录之前看到'user_logged_in'为false,那么一旦用户登录,我如何重新评估它?我不希望刷新页面,而希望刷新某种同步类型的评估。
谢谢!!让我知道我该如何澄清!