在继续之前将全局数据设置为来自获取请求的属性 [英] Set global data to property from get request before continue

查看:68
本文介绍了在继续之前将全局数据设置为来自获取请求的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一项共享服务的应用程序,可以帮助我在所有组件之间共享数据

I have an angular app with one shared service to help me share data across all components

共享服务

@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属性. 因为该应用程序使用userData,所以我想在执行其他操作之前先完成设置此属性.

The userData property is set after an observable request completed. Because the app uses the userData I would like to complete set this property before execute other things.

完成此任务的最佳方法是什么?有没有办法进行同步http调用?

What is the best way to accomplish this? Is there a way to make synchronous http call instead?

推荐答案

具有四个服务

  1. 全球
  2. UserService
  3. HttpUtil
  4. 身份验证

全球服务

@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;
        }

    }
}

UserService

UserService

@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');
    }
}

HttpUtil:定制的http服务,可跨应用程序进行通用处理

HttpUtil : Customized http service to handle generically across application

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;
            }

AuthenticationService-调用httpUtil,因此在整个应用程序中,您应该使用 HttpUtil ,而不是@angular/http

AuthenticationService - calls the httpUtil so through out application you should use HttpUtil and not Http from @angular/http

如果您需要更多说明,请告诉我

Let me know if you need any more explanations

这篇关于在继续之前将全局数据设置为来自获取请求的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆