我有一个带有一个共享服务的角度应用,可以帮助我在所有组件之间共享数据
共享服务
@Injectable()
export class ShareService {
userData: [];
selectedMonth: number;
selectedYear: number;
}
用户服务
@Injectable()
export class UserService {
baseApiUrl = environment.api_base_url;
constructor(private http: Http, private cookie: CookieService) { }
getUserData() {
return this.http.get(this.baseApiUrl + 'api/get-user-data' + this.cookie.get())
.map((res: Response) => res.json());
}
AppComponent
export class AppComponent implements OnInit {
isAuth: boolean = false;
isAdmin: boolean;
constructor(private auth: AuthService,
private user: UserService,
private share: ShareService) {
}
ngOnInit() {
this.setUser();
}
setUser() {
this.user.getUserData().subscribe(
(data) => {
this.share.user = data;
console.log(data);
}
);
}
}
在完成可观察请求后设置userData属性。 因为app使用userData,我想在执行其他事情之前完成设置此属性。
实现这一目标的最佳方法是什么?有没有办法进行同步http调用?
答案 0 :(得分:3)
有四项服务
全球服务
Product
UserService
@Injectable()
export class Global {
constructor(private userService: UserService, private router: Router) {
if (!this.isAuthenticatedUser()) {
this.router.navigateByUrl('/login');
}
}
handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || 'Internal Server error');
}
isAuthenticatedUser(): boolean {
let user = this.userService.getUser();
if (_.isEmpty(user)) {
return true;
} else {
return false;
}
}
}
HttpUtil:自定义http服务,可以跨应用程序进行处理
@Injectable()
export class UserService {
constructor() { }
setUser(user: User) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
getUser(): User {
// get the current user from local storage to keep user logged in between page refreshes
return <User>JSON.parse(localStorage.getItem('currentUser'));
}
clearUser() {
localStorage.removeItem('currentUser');
}
}
AuthenticationService - 通过out应用程序调用httpUtil,你应该使用 HttpUtil 而不是来自export class HttpUtil {
private headers: Headers;
constructor(
private globalConstants: GlobalConstants,
private http: Http,private userService: UserService,
private global: Global) {
this.headers = new Headers(
{ 'Content-Type': 'application/json' },
);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
if (this.global.isAuthenticatedUser()) {
let token = this.userService.getUser().token;
this.headers.append('Authorization', 'JWT ' + token);
if (!options) {
this.headers.forEach((header: any) => {
options.headers.append(header.name, header.value);
});
options.withCredentials = true;
}
return this.http.get(url, options);
}
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
if (this.global.isAuthenticatedUser()) {
let token = this.userService.getUser().token;
this.headers.append('Authorization', 'JWT ' + token);
if (!options) {
this.headers.forEach((header: any) => {
options.headers.append(header.name, header.value);
});
options.withCredentials = true;
}
的{{1}}
如果您需要更多解释,请告诉我