ActivatedRoute is an Angular service that gives a component access to information about the route currently displayed. Inject it into a component when its behavior depends on the URL, such as choosing between creating and editing a product. section 7.5.4 section 24.3.1
Use the route object and its snapshot to inspect:
- snapshot, an ActivatedRouteSnapshot describing the current route. section 24.3.1
- url, an array of UrlSegment objects representing the matched URL segments. section 24.3.1
- params, URL parameters indexed by name; queryParams, query-string parameters; and fragment, the URL fragment. section 24.3.1
- Each UrlSegment exposes its path value and an indexed collection of parameters. section 24.3.1
Selecting create or edit mode
A product editor receives ActivatedRoute in its constructor, then reads snapshot.params["mode"] to determine whether it is editing. When editing, it reads snapshot.params["id"] and loads the matching product from the repository. The component can therefore display either a blank product or existing product details without relying on a separate component-to-component event. section 7.5.4 section 24.3.1
Listing 7.36. Adding functionality in the productEditor.component.ts file in the src/app/admin folder
import { Component } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { Product } from "../model/product.model";
import { ProductRepository } from "../model/product.repository";
@Component({
templateUrl: "productEditor.component.html"
})
export class ProductEditorComponent {
editing: boolean = false;
product: Product = new Product();
constructor(private repository: ProductRepository,
private router: Router,
activeRoute: ActivatedRoute) {
this.editing = activeRoute.snapshot.params["mode"] == "edit";
if (this.editing) {
Object.assign(this.product,
repository.getProduct(activeRoute.snapshot.params["id"]));
}
}
save() {
this.repository.saveProduct(this.product);
this.router.navigateByUrl("/admin/main/products");
}
}
Inspect the complete product-editor implementation, including ActivatedRoute injection, snapshot parameter access, product loading, and saving. section 7.5.4
