Strategies for handling HTML content in the getProduct API call using Angular resolve

Components and Services Setup

export class ProductComponent implements OnInit {
  
      constructor(
        private route: ActivatedRoute,
        private router: Router,
      ) { }
    
      ngOnInit() {
        this.route.data
          .subscribe(
            (data: Data) => {
              this.router = data['product'];
            }
          );
      }
    }
    

I'm currently working on the HTML structure for the product component and could use some guidance.

<div class="productContainer">
        <img class="productContainer__image" src="img">
    
        <div class="innerContainer">
            <p class="innerContainer__text">text</p>
            <label class="innerContainer__text">Size:</label>
            <app-select [options]="['XS', 'S', 'M', 'L', 'XL']" placeholder="Size" width="100px"></app-select>
            <label class="innerContainer__price">Price: 40$</label>
            <div class="buttonContainer">
                <button class="buttonContainer__button">Add to bag</button>
            </div>
        </div>
    </div>
    

HTTP ProductService

   public getProduct(id: string): Observable<IGetProductResponse> {
            const baseUrl = ENDPOINT;
    
            return this.http.get<IGetProductResponse>(baseUrl + id);
        }
    

Product Service and Resolver

  public getProduct(id: string): Observable<IProductInterface> {
        return this.httpProductService.getProduct(id)
          .pipe(catchError((errorResponse: HttpErrorResponse) => {
            let errorMessage: string;
    
            switch (errorResponse.status) {
              case 400:
                errorMessage = 'error 400';
                break;
              default:
                errorMessage = 'other error';
            }
    
            return throwError(errorMessage);
          }),
            map((response: IGetProductResponse) => response.data!),
          );
      }
    

Product Resolver

@Injectable()
    export class ProductResolver implements Resolve<IProductInterface> {
    
        constructor(private productService: ProductService) { }
    
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IProductInterface> {
            return this.productService.getProduct(route.paramMap.get('id')!);
        }
    }
    

If you need more details or have any questions, feel free to ask. Thanks for the assistance!

Answer №1

Start by setting up the product in your component:

    this.activatedRoute.data.subscribe(data => {
          this.product= data.product;
})

After defining the product, you can simply use 'product' in your HTML:

<div>{{product.name}}</div>

Remember to include the product resolver in your routing configuration:

{
        path: "product/:id", component: ProductComponent,
        resolve: {
          product: ProductResolver,
        }
      },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When submitting a form, the MEAN STACK backend is storing the objectId and __v : 0 in MongoDB

Currently, I am developing a small CRUD application using the MEAN STACK framework. My goal is to create a form that allows me to store book information in MongoDB. However, upon submission, I noticed that instead of saving the book's details, the dat ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

Adding an additional element to an object - crossroads of combining types versus sequential examination

Here's a query for you: AppendToObject. When I first tackled this question, my initial instinct was to utilize type intersection like so: type AppendToObject<T, U extends PropertyKey, V> = T & {[P in U]: V} Unfortunately, this solution did ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...

Is there a way to verify if a property shares the same value as another item within an object array using ajv?

I am currently working on creating a JSON schema to validate cross references using AJV and TypeScript. Is there a method to verify that a property includes another property from any item within the array (not a specific item in the array)? Both the prop ...

Sending updated data from modal back to child component

Within my parent component, I have two child components: Child0 and Display. Child 0 consists of a single button that triggers the opening of a modal where users can select items from a list. The Display component, on the other hand, only contains a label ...

Angular 8 wild card redirect problem with Routable Modals

I have a Modal that can be routed with unique parameters to display Training content defined in the app-routing.module.ts file { path : 'TopshelfContent/:catName/:cmsID', component: ModalContainerComponent, canActivate: [MsalGuard]}, When manua ...

How can I resolve the Http-Server npm command problem?

After attempting to deploy my Angular application locally and running the npm-build command to generate a 'dist' folder, I encountered an error when trying to execute the http-server command. I have tried changing the port number, clearing the c ...

Creating a Jira-inspired table layout in Angular by embedding components in a structured format

I'm attempting to recreate the functionality of Jira where I can create a "gadget" that can be added to a board, resized, moved, and deleted. (For those unfamiliar with why this might be useful, think of gadgets like the "Gantt" gadget. You can add a ...

Encountering TS7053 error while trying to access component variables using type indexing in Angular 13

When trying to access a variable with type indexing in Angular 13, I encountered a TS7053 error. However, in this Stackblitz example, the same code works without any errors. export class AppComponent { name = 'Angular ' + VERSION.major; Pro ...

Searching for a specific MongoDB document based on an element within an array

https://i.sstatic.net/1gv6N.png This individual's notes are stored in a database. I am attempting to retrieve only the notes marked with "activeFlag:1" for this specific user. Below is my code for the query object: findAccountObj = { _id: objectID( ...

What is the best way to access the data being sent to a router link in Angular?

After navigating to the user page using the router sample below, how can I retrieve the details once it reaches the user page? I need to verify in my user.component.ts that the navigation is triggered by this [routerLink]="['user', user.id, &apo ...

Alternatives to using wildcards in TypeScript

In my code, I have defined an interface called ColumnDef which consists of two methods: getValue that returns type C and getComponent which takes an input argument of type C. Everything is functioning properly as intended. interface ColumnDef<R, C> { ...

Differences between Integrated and Isolated Testing in Angular 2

Can you explain the key distinctions between Integrated testing and Isolated testing? In what scenarios would these testing methods be recommended for use? ...

TypeScript's robustly-typed rest parameters

Is there a way to properly define dynamic strongly typed rest parameters using TypeScript 3.2? Let's consider the following scenario: function execute<T, Params extends ICommandParametersMapping, Command extends keyof Params, Args extends Params[C ...

Error 404: Angular 2 reports a "Not Found" for the requested URL

I am currently in the process of integrating an Angular 2 application with a Java Spring Boot backend. As of now, I have placed my Angular 2 files under src/main/resources/static (which means that both the Angular and Spring apps are running within the sam ...

Using useEffect with promises causing TypeScript errors

useEffect(login, []) In this case, the login function returns a promise and the useEffect hook is triggered without expecting a return value. However, TypeScript shows errors like: Argument of type '() => Promise<void>' is not assi ...

I am facing an issue where Node.js and mongoose are unable to retrieve data from MongoDB

Could you please assist me in locating the code for app.js? var express = require('express'), routes = require('./routes'); var mongoose = require('mongoose'); var app = module.exports = express.createServer(); // Configurat ...

What is the best way to convert a string to a number in MongoDB using $project in aggregation?

As someone who is new to using mongoDB, I am trying to convert a string field value (int, float, or long) in order to make comparisons and assign the result to a new field. However, despite my hours of attempts, I have been unsuccessful so far. Here&apos ...

When attempting to incorporate the "active" class into a Bootstrap 4 carousel using jQuery, issues arise specifically when retrieving data from a MongoDB database

I'm working on a carousel feature where I need to load images from my MongoDB database. However, the issue I'm facing is that even though I've tried adding the active class to the first item, the carousel doesn't transition to display t ...