我的组件订阅了一个服务,该服务调用api来获取一些值。在api调用之前,我想检查我的appStore是否已经拥有这些数据以避免无用的呼叫,但无法找到使其工作的方法。
我该怎么做?
这是我的组成部分:
import { UserService } from '../../core/user.service';
@Component({
...
})
export class AnagraficaComponent implements OnInit {
userData: any;
constructor(private userService:UserService) { }
ngOnInit() {
this.userService.getUserData(1)
.subscribe(result => {
this.userData = result;
});
}
}
这是我的服务:
import { CURRENT_USER } from '../app.actions';
interface AppStore {
currentUser: any;
}
@Injectable()
export class UserService {
currentUser: Observable<any>;
constructor(private http: Http, private store: Store<AppStore>) {
this.currentUser = store.select('currentUser');
}
getUserData(id: number): Observable<any> {
// TODO: user store
// check if there is a current user in store (means is already logged in)
// if true return data from store
/*
return this.currentUser
.map(user => {
return user;
});
*/
// else return data from server
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token);
let options = new RequestOptions({ headers: headers });
return this.http.get(myGlobals.API_URL + 'user/' + id, options)
.map((response: Response) => {
// TODO : check response
// update store with current user from server
// this.store.dispatch({ type: CURRENT_USER, payload: userData });
return response.json().data;
});
}
}
答案 0 :(得分:0)
为什么不这样测试:
import { CURRENT_USER } from '../app.actions';
interface AppStore {
currentUser: any;
}
@Injectable()
export class UserService {
currentUser: Observable<any>;
constructor(private http: Http, private store: Store<AppStore>) {
this.currentUser = store.select('currentUser');
}
getUserData(id: number): Promise<any> {
return new Promise<any>((resolve,reject)=>{
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if(currentUser){
resolve(currentUser);
return;
}else{
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token);
let options = new RequestOptions({ headers: headers });
return this.http.get(myGlobals.API_URL + 'user/' + id, options)
.map((response: Response) => {
localStorage.setItem('currentUser', JSON.parse(response.json().data));
// this.store.dispatch({ type: CURRENT_USER, payload: userData });
resolve(response.json().data);
return ;
});
}
});
}
}
答案 1 :(得分:0)
您可以创建一个具有私有行为主题的UserStore并公开显示它的可观察性,然后在每次调用时首先检查您是否已经在User subject中有数据,如果不仅仅是调用该服务。并且在组件级别调用thius存储而不是服务
import { UserService } from '../../core/user.service';
export class UserStore {
private _user: BehaviorSubject<User> = new BehaviorSubject(null);
constructor(
private userService: UserService
) {
this.loadInititalData();
}
get user() {
return this._user.asObservable();
}
loadInititalData() {
let user: User = this._user.getValue();
if (!user) { // only if value doesn't exist on the client
this.userService.get()
.subscribe(
res => {
this._user.next(res);
},
err => this.handleError(err, "loadinitialdata UserStore")
);
}
}
private handleError(error: any, src: string) {
console.log(src + ": " + error)
}
}