Using JSON to Map Routes in Angular 2

Service:

export class ArticlesService {
  private _url = 'https://example.firebaseio.com/.json';

  constructor(private _http: Http) {
  }

  getAllArticles(): Observable<any> {
    return this._http.get(this._url)
      .map((response: Response) => response.json())
      .catch((error) => Observable.throw(error));
  }

  getAnArticle(articleId: any): Observable<any> {
    return this._http.get(this._url.replace(".json", articleId + ".json"))
      .map((response: Response) => response.json())
      .catch((error) => Observable.throw(error));
  }
}

Component:

theArticle = {};

  constructor(private _activatedRoute: ActivatedRoute, private _articlesService: ArticlesService, private _router: Router) {
    this._router.events
      .filter(theEvent => theEvent instanceof NavigationStart)
      .subscribe((theEvent: NavigationStart) => {
        if (/\/articles\/\d/.test(theEvent.url)) {
          const urlDetails = theEvent.url.split('/');
          const articleId = urlDetails[urlDetails.length - 1];
          this.getArticleDetails(articleId);
          console.log(this.theArticle);
        }
    });
  }

  ngOnInit() {
    this.getArticleDetails(this._activatedRoute.snapshot.params['id']);
  }

  getArticleDetails(articleId: any) {
    if (articleId != null ) {
    this._articlesService.getAnArticle(articleId - 1)
      .subscribe(data => {
        this.theArticle = data;
      });
    }
  }

Router:

{ path: 'articles/:id', component: PArticlesComponent }

HTML:

(navigation)

<ul class="sidebar-ul" *ngIf="allArticles.length">
  <li *ngFor="let anArticle of limit(allArticles)">
    <a [routerLink]="['/articles', anArticle.id]">{{anArticle.title}}
      <br/>
      <span class="date">{{formatDate(anArticle.createdOn)}}</span>
    </a>
  </li>
</ul>

(article)

<div *ngIf="theArticle.id">
  <h2 class="article-title">
    <a href="#">{{theArticle.title}}</a>
  </h2>
  <div class="meta">
    <p class="date">{{formatDate(theArticle.createdOn)}}</p>
  </div>
  <p [innerHTML]="theArticle.details"></p>
</div>

Explanation:

The getAnArticle function inside the ArticlesService uses the :id parameter of a selected article and sends that parameter to the getArticleDetails function inside of the component. The getArticleDetails function then uses that param to subscribe the contents of that JSON object. This object looks like this:

{"id":"5","createdOn":1494721160,"title":"title 5","details":"details 5","shorthand":"shorthand-5"}

Note that this is the 5th object in the JSON file, so it's key id is 4, which is why I'm subtracting the value by 1 in the getArticleDetails function.

This all works great, and when an article is clicked the router updates properly to show a URL such as http://www.example.com/articles/5 but I'm having a real hard time modifying the code so that the URL instead displays http://www.example.com/articles/shorthand-5.

I can get the router to have proper URL's but since right now I'm easily working with a static number and subtracting that value by 1 to get the correct JSON object, I can't figure out how to read the correct data (or any data for that matter) by using the :shorthand parameter as the identifier.

Answer №1

One possible solution is to create a server-side endpoint that can fetch articles based on a provided shorthand code. This way, when a user enters a URL containing the shorthand code, your application can retrieve the corresponding article. You could also add a new method in the ArticlesService class to make requests to this endpoint (e.g., getArticleFromShorthand).

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

How to position GeoJson in the center of a Google Map on Android

As a newcomer here, I'd appreciate some understanding if this question has been asked before (which is unlikely) or if I'm approaching it incorrectly as a newbie. Here's the issue: I want to center my geojson on Google Maps Android. Here& ...

Create a data structure to encompass every conceivable object property category

Upon hovering over the typeof for a random object property, we are presented with a range of potential types: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" https://i.sstatic.net/0qnKa.jpg Is there a way to d ...

Having trouble grasping the inner workings of code while iterating through a JSON array in ReactJS

Currently, I am immersed in a school project that requires me to develop a simple CRUD web application. After weighing my options, I decided to utilize Spring Boot + ReactJS for this endeavor. The progress has been smooth so far, but I must admit that part ...

Developing a Progressive Web App with ASP.NET Core 3 and Angular is a powerful

I have embarked on the journey of building an Angular SPA in ASP.NET Core 3. To kick things off, I created a new project, utilized the Angular template, and upgraded all packages to version 8.2.9 of Angular. Setting up a seamless CI/CD pipeline to Azure wa ...

Setting the status code in Angular 6 Server Side Rendering (SSR) from a Component

Is it possible to customize status codes like 404, 401, and 500 as needed? I am currently working with Angular 6 and have come across outdated tutorials that do not provide solutions that work. These tutorials often refer to a server.ts file that is no lo ...

Angular 2 router hybrid application: URL resets after navigation

Each time a route is changed, the correct component is rendered but there seems to be an issue with the path. For example, when navigating from /items to /add-item, the URL changes momentarily but then reverts back. This issue occurs on every page, reg ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

The Angular2 - Webpack - Cordova Hybrid App is showing a white screen following the splash screen. It appears that the rendering of the HTML DOM

When working with Angular2-Cordova, I encountered an issue where the hybrid app would display a white screen for at least 20 seconds before showing the app content. Upon inspecting the app in the browser web console, the following points were observed: T ...

Sorting the table header in Angular 12 is not defined

Currently, I am in the process of upgrading from Angular 8 to 12 and have encountered several errors during this transition. While most of them have been resolved successfully, there is one remaining issue which can be viewed here. The specific error that ...

How can we reduce the size of JSON array messages?

When working with JSON to transmit an array of objects from the same class, I've noticed that the fields of the objects are repeated multiple times unnecessarily. This results in very long messages, especially for arrays with a large number of element ...

Utilize CSS Styles with Angular 2 Component Selectors

I'm currently diving into Angular 2 and I've been pondering the idea of implementing CSS styles using the component selector in this manner: the component @Component({ selector: 'app', styleUrl: './local.css', te ...

The database was queried and 4700 records were successfully retrieved in JSON format

My android application is using the following code to read and import 4700 records from a MySQL database on the web with a JSONArray: @Override protected String doInBackground(Void... params) { try{ httpclient = new Def ...

How can you set up multiple router-outlet instances in Angular without explicitly naming them in the routing configuration?

As an illustration, in this particular project showcased at this link, The functionality of multiple routing is functioning as intended. However, upon clicking the Product Link, the URL shifts from: to I am looking to eliminate the addition of (sidebar: ...

Guidelines for Parsing JSON Arrays with Parent-Child Relationships in Java

This Json text contains key information such as "name, surname, and books" stored as an Array. However, the issue arises when handling the 'books' field, which is also an array with a specific format: {"title:heresometext",paragraphs{value1:heres ...

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

Issues with my POST function across different domains

I have developed a MVC rest Web API with a method structured like this: public HttpResponseMessage PostBook(DtoBooks Book) { if (Book == null) { return Request.CreateResponse(HttpStatusCode.BadRequest); ...

The PrimeNG dialog component stubbornly refuses to close even when clicking outside the modal

My modal dialog component from PrimeNG is structured like this <p-dialog header="{{title}}" [(visible)]="display" [modal]="true" [dismissableMask]="true" [closeOnEscape]="true" [responsive]="true" [closable]="false" > {{content}} </p-dialog&g ...

Guide on Springboot backend: Receiving an array-containing object from frontend in JSON format

I have encountered an issue with data transfer between the Front End and Back End while developing a fullstack Web application for selling clothes. In my Vue application, I send a JSON object to the Backend in the following format: { "customer": ...

Encountering a Validation Error while Creating a Progressive Web App using Ionic CLI

I'm trying to build a simple PWA app using the IONIC Framework, but have been struggling to make it work. I am still new to Ionic and have followed various tutorials from different sources without success. If you want to check out the tutorials I&apo ...

Invoke a function once a series of functions have finished executing in Angular 8

As a beginner in Angular, I am facing a challenge in calling a function after a series of functions have completed their execution. Although I don't require these functions to run sequentially, I do need to trigger another function once all of these f ...