Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For example,

[routerLink]="['page', item.fields.id]"
. What I aim to achieve is to include a next button on the generated page that navigates to the next item's generated page.

Here's how my setup looks...

contentful.service.ts

This file handles my API calls:

// Retrieve all program items
getProgramItems(query?: object): Promise<Entry<any>[]> {
    return this.cdaClient.getEntries(Object.assign({
      content_type: CONFIG.contentTypeIds.programItems
    }, query))
    .then(res => res.items);
}

// Fetch only program items with a specific week
getWeekItems(week: number): Promise<Entry<any>[]> {
    return this.getProgramItems({'fields.week': week});
}

// Obtain program with a certain ID
getAsset(id: string): Promise<Entry<any>[]> {
    return this.getProgramItems({'sys.id': id});
}

week-1.component.ts

This section involves fetching data and displaying the list of items:

export class Week1Component implements OnInit {
  private programItems: Entry<any>[] = [];
  private week1Items: Entry<any>[] = [];

  constructor(
    private contentfulService: ContentfulService
  ) { }

  ngOnInit() {
      this.contentfulService.getWeekItems(1)
      .then((week1Items) => {
        // Set week1Items and order them by sequenceOrder
        this.week1Items = _.orderBy(week1Items, ['fields.sequenceOrder'], ['asc']);
        })
      .then(() => {
        console.log(this.week1Items);
      });
  }

week-1.component.html

This area displays the list items and includes the routerLink for dynamic page creation:

<div class="program_card" *ngFor='let item of week1Items'>
...

asset-page.component.ts

export class AssetPageComponent implements OnInit {
  asset: Entry<any>[];

  constructor(
     private contentfulService: ContentfulService,
     private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.route.paramMap
    .switchMap((params: ParamMap) => this.contentfulService.getAsset(params.get('id')))
    .subscribe(asset => {
      this.asset = asset;
      console.log(this.asset);
    });
  }

}

In essence, what I am trying to accomplish is to have a next button on the dynamically created asset page that directs to the following dynamically generated asset page from the list on the week-1 page. Any assistance or suggestions would be greatly appreciated! Feel free to request additional information if needed.

Thank you!

Answer №1

To ensure seamless access to the response from getProgramItems, consider storing it in a state management service or within the data-fetching service itself. This approach enables any component utilizing the service to readily retrieve the data. Additionally, you may opt to extract the dynamic link into a directive for easy incorporation of program items.

Explore various state management services available for Angular.

If data sharing between components becomes frequent, exploring tools like NGRXStore is recommended. This tool facilitates efficient management of API data shared across different sections of your application.

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

A guide to extracting iFrame information (specifically the referring URL) using JavaScript

Is there a way to retrieve the information from an iFrame (right-click on an iFrame in the browser -> This Frame -> View frame info)? I'm particularly interested in obtaining the referring URL. So far, I managed to retrieve the address using co ...

What is the most effective way to extract content values from different divs for calculation using jQuery?

I am working on creating a function that retrieves the content values from the <div class="rowtabela"> div and reads the nodes of <div class="item v_...">. Check out my code below: <div class="adicionados" id=& ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

"Creating a function within a knockout viewmodel that is populated with JSON data: A step-by-step guide

Struggling with defining a function inside my viewmodel. I retrieve json data using jquery getJSON and then map it to the viewmodel. $.getJSON('/Company/GetCompanies', function(data) { var viewModel = new CompanyViewModel() viewModel.m ...

The transformation rotation applied in CSS must not have any impact on the styling of my span and paragraph

Snippet: .details-section{ background-color: rgb(83, 83, 83); height: 200px; } .icon-container{ border: 2px solid #c49b63; width: 90px; height: 90px; transition: 0.5s ease; } .box i{ font-size: 60px; color: black; margin-top: 13px ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

How to trigger a click event in React using TypeScript and material-ui library

Currently, I am facing an issue when trying to update the value of material-ui TextFields from the store. When manually typing inside the field, everything works fine as expected with the handleChange() and handleBlur() functions handling the events. Howev ...

Encountering an error with the iconv-lite package in TypeScript code

I recently added the "iconv-lite" package to my project, imported the module, and attempted to use the decode method. However, I encountered the following error: TypeError: Cannot read properties of undefined (reading 'decode') Interestingly, ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Tips for eliminating whitespace from an input field and then updating the field with the trimmed value

Currently, I am working on email validation where users might input empty spaces in the email field. To address this issue, I have implemented a logic to trim the input value using $trim and then re-assign it to the input field. Although everything seems ...

If there are no visible layers, OpenLayers will not recognize zoom scroll events

I have observed that when all OpenLayers.Layers are set to invisible, I lose the ability to zoom in and out using the mousewheel. Although I can still use the OpenLayers.Control.Zoom buttons, the mouse wheel functionality is disabled. Is there a way to de ...

What sets $emit and $dispatch apart in Vue.js?

Vue 2.0 has deprecated the use of $dispatch and $broadcast. I have noticed that $dispatch is similar to $emit. What are the key differences between them? Can we safely replace $dispatch with $emit during migration? ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder=== ...

The HTML and JavaScript implementation of the Game of Life is experiencing technical difficulties

I attempted to create my own version of the Game of Life using HTML canvas and JavaScript. With the aid of various online tutorials, I was able to write a piece of code that I am still confident in. However, upon launching the HTML page in the browser and ...

Can a href from a "<Link>" component be passed through a Higher Order Component (HOC) into an "<a>" tag?

I am currently facing a situation with the main component where I have the following code: <Link href={'test'}> <PrimaryAnchor>Welcome</PrimaryAnchor> </Link> Within the PrimaryAnchor component, the code looks like ...

A step-by-step guide on retrieving a value from a DateTime picker in a React application

I am utilizing Material-UI to create a DateTime picker. You can check out my demo code here. In order to observe the current selected value, I have added console.log to the function handleChange. However, I am facing an issue where the value does not chan ...

Error encountered while trying to retrieve Instagram JSON data via request due to an abrupt end of input

I am attempting to retrieve the JSON data from Instagram's URL: . When I enter this URL in my browser, it displays the JSON information. However, I want to be able to access this data using Express so that I can extract any necessary information. co ...

Reorganizing divisions with Dojo

I came across a thread on StackOverflow that was similar to what I'm looking for. jQuery removing an element and renumbering remaining elements However, since we don't use jQuery but instead rely on Dojo, I'm unsure how to achieve the same ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...