Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

angular - Set global data to property from get request before continue

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

Shared service

@Injectable()
export class ShareService {
  userData: [];
  selectedMonth: number;
  selectedYear: number;
}

User Service

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have four services

  1. Global
  2. UserService
  3. HttpUtil
  4. Authentication

Global service

@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

@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 : 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 - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...