What is the reason for my Angular2 application not being able to locate my model?

An error occurred: XHR error (404) loading

Access the Plnkr link here: https://plnkr.co/edit/gwa3NWArtWK0wjf2jr2h?p=preview

I have created a file named models/home.ts

https://i.sstatic.net/FQlgi.png

The file includes:

export function homeData() {
  return [
    { id: 0,
      title: '2017 Oscars',
      graphic: 'https://wikitags.com/images/OscarsBanner.png',
      categorycards: [
        {
            type: 'image',
            graphic: 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg/1024px-Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg?width=440',
            title: '2017 Oscar Nominee for Best Actor',
            listings: ['Rayn Gosling', 'Denzel Washington', 'Andrew Garfield', 'Casey Affleck', 'Viggo Mortensen']
        },
        {
            type: 'image',
            graphic: 'https://commons.wikimedia.org/wiki/Special:FilePath/Meryl_Streep_February_2016.jpg?width=440',
            title: '2017 Oscar Nominee for Best Actress',
            listings: ['Meryl Streep', 'Emma Stone', 'Natalie Portman', 'Ruth Negga']
        },
        {
            type: 'image',
            graphic: 'https://commons.wikimedia.org/wiki/Special:FilePath/Dev_Patel_(29870651654).jpg?width=440',
            title: '2017 Oscar Nominee for Best Supporting Actor',
            listings: ['Dev Patel', 'Jeff Bridges', 'Michael Shannon', 'Lucas Hedges', 'Mahershala Ali']
        },
        {
            type: 'image',
            graphic: 'https://commons.wikimedia.org/wiki/Special:FilePath/Michelle_Williams_by_Gage_Skidmore.jpg?width=440',
            title: '2017 Oscar Nominee for Best Supporting Actress',
            listings: ['Michelle Williams', 'Nicole Kidman', 'Viola Davis', 'Octavia Spencer']
        }
      ]
    }
  ];
}

After that, in my categoryService.ts, I imported it like this:

import {Injectable} from 'angular2/angular2';
import {Http} from 'angular2/http';
import {homeData} from 'models/home'; // <- Correct path set here

@Injectable()
export class CategoryService {
  constructor(http:Http) {
    this.categories = http.get('api/categories.json').map(res => {
      // console.log(res)
      // return res.json();
      return res.send(homeData());
    });
  }
}

However, it appears to be unrecognizable

https://i.sstatic.net/FQlgi.png

Answer №1

Relocate your models directory to the src directory,

then follow these steps:

import {homeData} from './models/home';

All your code should be within the src directory as indicated in your config.js file where you specify to System.js that your app is located in the src directory:

//config.js
map: {
    app: "./src"
  },

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

Tips for accessing the StaticRouterContext in Typescript with react-router-dom

Currently, I am implementing SSR for my app specifically targeting robots. There is a possibility that the render of the <App/> component may lead to a route not being found. In order to handle this scenario, I need to identify when the render ends ...

Navigating json data in angular 6

I retrieved a JSON object in the following format response = [ { 'a': [ { 'b': [ { 'c': [ { 'name': 'abc', 'value': 900 ...

How can I implement a method to configure a 404 HTTP header in Angular 5 when a route is not found?

Is it possible to display a custom 404 header on the current page when there is no route matching my array? If not, could this potentially create SEO issues and have unknown pages indexed by search engines? ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

Using Angular with adal-angular4 and implementing refresh token functionality

I have incorporated the Azure AD authentication in my Angular application using the package mentioned below: https://www.npmjs.com/package/adal-angular4 However, I am facing an issue where the token expires after 10-20 minutes. I have searched through va ...

Unclear error message when implementing union types in TypeScript

Currently, I am attempting to define a union type for a value in Firestore: interface StringValue { stringValue: string; } interface BooleanValue { booleanValue: boolean; } type ValueType = StringValue | BooleanValue; var value: ValueType = { bo ...

Supply additional parameters to the method decorator within an Angular component

Imagine a scenario where there are multiple methods requiring the addition of a confirmation dialog. In order to streamline this process, a custom decorator is created. @Component({...}) export class HeroComponent { constructor(private dialog: MatDialog ...

Unable to connect dynamic information in Angular 8 component

Error encountered during dynamic component loading DynamicBuilderComponent.ngfactory.js:198 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: The expression has changed after it was checked. Previous value: 'ng-pristine: true'. Current ...

PhpStorm is unable to resolve the @ionic/angular module

I have encountered a peculiar issue with my Ionic v4 project. While the project runs smoothly, PhpStorm seems unable to locate my references to @ionic. https://i.stack.imgur.com/umFnj.png Interestingly, upon inspecting the code, I realized that it is act ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

The dynamic duo of Typescript and Express creates an unbreakable bond within a configuration

Trying to incorporate ES6 modules into my app has been a bit frustrating. Initially, I attempted setting "module": "es2020" or "module": "esnext", only to encounter an error instructing me to specify "type": "module" in the package.json file or use the .m ...

Encountered an error while trying to access the 'touched' property of undefined within Angular6 reactive forms

When attempting to validate my page, I encountered an error stating 'Cannot read property 'touched' of undefined'. Can someone please assist me with this code? Also, feel free to correct any mistakes you may find. Here is the HTML code ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Creating image paths for a list of items in reactjs can be achieved by mapping through the list

My goal is to display a list of items, with each item being assigned an image based on its ID: private static renderItemsTable(products: Product[]) { return <table className='table'> <thead> <tr> ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

In Angular 2, how does the "this" keyword from the subscribe method reference the class?

I am using a subscription for Observable, and when it finishes I need it to call a function from this class. The issue is that the "this" keyword refers to the subscription and not to the class scope. Here is the code snippet: export class GoogleMapCompo ...

Encountering a Cross-Origin Resource Sharing issue involving the Access-Control-Allow-Origin * setting in NodeJS and Angular

I'm currently working on a web application using Angular, and I encountered a CORS error when trying to connect the backend with the front end: Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://lo ...

Put Angular4 (Angular) that has been developed with angular-cli onto Google App Engine

After creating an Angular4 application using Angular-CLI, I was able to run it locally with "ng serve" and everything worked perfectly. Now my goal is to deploy it to Google App Engine, where ng build --prod compiles all files into a dist folder. My quest ...

Experiencing the issue of receiving unexpected commas following a div

Here is the code written in TypeScript for creating an HTML table that displays items from nested objects. The code is functional, but there seems to be an issue with extra commas being printed which are not part of any specific line being executed. im ...