我有一個共享服務的角度應用程序,以幫助我在所有組件共享數據設置全局數據從GET請求屬性之前繼續
共享服務
@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我想在執行其他事情之前完成設置此屬性。
完成此操作的最佳方法是什麼?有沒有辦法使同步http調用呢?
爲您的其他服務電話添加代碼 – Aravind
@Aravind我已經更新了我的答案 – marnaels
您想以這種方式解決還是替代方法? – Aravind