Hanzo
Hanzo

Reputation: 1899

Best/correct way to implement Master detail with Angular

I'm implementing a Master/detail UI with Angular 4(Material Design) for Frontend and Rest API Node/MongoDB for Backend

First I've request to server the list of categories that populate their product refs and returns to Frontend via JSON all the data

My doubt is about when a user clicks on a list element:

-Pass whole data of the product to render it via `queryParams`

-Pass whole data of the product to render it via injected local Data service

-Pass id of the product via URL an then request the info to server again

Which would be the normal flow on app?

Is there a better way to do it?

Upvotes: 3

Views: 1058

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71941

Even though this is primarily opinion based, the best way to do this is to pass the id of the product via the URL. This way you can have a direct link to the product as well. You can obtain the data using a resolve guard service which can prefetch component data.

If you are worried about double requests and you should, you can create a caching service which obtains the results from a memory stored product collection, and if it cannot find it there, request the data from the server.

untested example code

@Injectable()
export class ProductCollectionCache {

    public readonly products: Product[] = [];

    public async getProduct(id: number): Promise<Product> {
       let product: Product = this.products.filter(p => p.id === id)[0];
       if (!product) {
           product = await this.productGetterService.getProduct(id);
       }
       return product;
    }

    public async getProductCollection(): Promise<Product[]> {
       //get collection or return cached
    }

}

On the other hand, if you are on the master form, you can obtain all the data from the server, and put this in the cache service

Upvotes: 3

Related Questions