Hi all,
I've just started learning the latest version of Angular and I'm working on
my first little project so this is all new to me.
I want to refactor the storeService.getStores() function so that I can
simply request the specific store that I want and the service will return
it. This is what I currently have which is returning the specific store, I
basically just want to put that in the service:
export class StoreDetailComponent implements OnInit {
store: IStore;
stores: IStore[] = [];
errorMessage: string;
constructor(private storeService: StoreService, private route:
ActivatedRoute, private router: Router) {}
ngOnInit() {
console.log('ngOnInit()');
let id = +this.route.snapshot.paramMap.get('id');
this.storeService.getStores().subscribe({
next: stores => {
this.stores = stores;
for(let i=0;i<this.stores.length; i++){
if(this.stores[i].storeId == id){
this.store = this.stores[i];
}
}
},
error: err => this.errorMessage = err
});
}
}
I was thinking that it would look something like this but I can't get it to
work:
export class StoreService {
private storeUrl = 'api/stores/stores.json';
store: IStore;
stores: IStore[] = [];
constructor(private http: HttpClient){
}
/*
getStore(id: number): Observable<IStore[]> {
let test = this.http.get<IStore[]>(this.storeUrl).pipe(
tap(data => console.log('All: ' + JSON.stringify(data))),
catchError(this.handleError)
);
for(let i=0;i<test.length; i++){
if(test[i].storeId == id){
this.store = test[i];
console.log(this.store)
}
}
return this.store;
}
*/
I'm thinking the invocation in the StoreDetailComponent would look
something like this:
ngOnInit() {
let id = +this.route.snapshot.paramMap.get('id');
this.store = this.storeService.getStores(id);
}
Can anyone help with the refactoring? My commented out code isn't working
and I've hit a bit of a brick wall.
The navigation menu has a list of the stores and clicking each one should
show the relevant store detail but it only shows the first one that's
clicked because ngOnInit() is only run once. Clicking on other navigation
links and then back to a store menu item will then show other store
details. How can change my code so that clicking each store will show the
correct store detail without having to click to another navigation menu
item?
Thank you for any help with this.
Graeme :)
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/angular/91b17556-c907-470c-90e0-f7e408d449f7%40googlegroups.com.