Base solution for your next web application
Open Closed

Client Side JSON to HTML in Angular 2 #3143


User avatar
0
btg created

Hello,

I'm trying to get information contained in a JSON document to display information as a module on a dashboard on the Angular 2 project. I can get code to compile, but I don't know where I'm going wrong to get it to display. Can anyone help me? :)

info-json.component.html

<div [@routerTransition]>

  <div class="card">
    <div class="header" *ngFor="let item of data">
      <h4 class="title" ng-model="item.name">{{item.name}}</h4>
      <p class="category" ng-model="item.city">{{item.city}}</p>
    </div>
    <p>Description.</p>
  </div>

</div>

info-json.component.ts

import { Component, Injector, AfterViewInit } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { Http } from '@angular/http';


@Component({
    templateUrl: './info-json.component.html',
    animations: [appModuleAnimation()]
})
export class InfoJsonComponent extends AppComponentBase implements AfterViewInit {


    constructor(
        injector: Injector,
        private _http : Http
    ) {
        super(injector);
    }

    public data: any[];

    ngAfterViewInit(): void {


        this._http.get("app/data/data.json")
            .subscribe((data) => {
                setTimeout(() => {
                    this.data = data.json();
                }, 1000);
            });
    }

}

dashboard.component.html

<div ng-include="'info-json.component.html'"></div>

main.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { DashboardComponent } from './dashboard/dashboard.component';

import { ModalModule, TabsModule, TooltipModule } from 'ngx-bootstrap';
import { AppCommonModule } from '@app/shared/common/app-common.module';
import { UtilsModule } from '@shared/utils/utils.module';
import { MainRoutingModule } from './main-routing.module';

import { InfoJsonComponent } from './dashboard/info-json.component';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        HttpModule,
        ModalModule,
        TabsModule,
        TooltipModule,
        AppCommonModule,
        UtilsModule,
        MainRoutingModule
    ],
    declarations: [
        DashboardComponent,
        CreateSlideModalComponent,
        InfoJsonComponent

    ]
})
export class MainModule { }

6 Answer(s)
  • User Avatar
    0
    alirizaadiyahsi created

    Hi,

    Is there error message anywhere? Can you provide us if there is an error message in your browser dev-console?

  • User Avatar
    0
    btg created

    <cite>alirizaadiyahsi: </cite> Hi,

    Is there error message anywhere? Can you provide us if there is an error message in your browser dev-console?

    No errors at all in the console. NG Live Development server compiles successfully. The HTML component doesn't show on the dashboard though.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    As far as I know, ng-include is for AngularJS and it is not available in angular 2. You need to set a selector for your component like this:

    @Component({
        selector: 'info-json',
        templateUrl: './info-json.component.html',
        animations: [appModuleAnimation()]
    })
    

    Then, you can use it in your other view like this:

    <info-json></info-json>
    

    Thanks.

  • User Avatar
    0
    btg created

    Aaah, I knew it was something I had overlooked. That fixed the display issue, but now I get an error that the resource cannot be found. Any thoughts on this, or should I open a new topic?

  • User Avatar
    0
    btg created

    <cite>btg: </cite> Aaah, I knew it was something I had overlooked. That fixed the display issue, but now I get an error that the resource cannot be found. Any thoughts on this, or should I open a new topic?

    I should be more specific. It seems as though my AJAX request is not able to find the file (easily fixable), but it the bigger issue is the information in the JSON is not accessible I guess. Do I need to run everything through the database, even if I just want to use a standable JSON from a feed??

    The error in console is:

    platform-content.js:682 post-publish handshake listeners already initialized
    jquery-migrate.min.js:2 JQMIGRATE: Migrate is installed, version 3.0.0
    2zone.js:2176 OPTIONS http://localhost:8080/assets/json/data.json 405 (Method Not Allowed)
    scheduleTask @ zone.js:2176
    ZoneDelegate.scheduleTask @ zone.js:384
    onScheduleTask @ zone.js:274
    ZoneDelegate.scheduleTask @ zone.js:378
    Zone.scheduleTask @ zone.js:209
    Zone.scheduleMacroTask @ zone.js:232
    (anonymous) @ zone.js:2200
    send @ VM10989:3
    (anonymous) @ http.es5.js:1254
    Observable._trySubscribe @ Observable.js:57
    Observable.subscribe @ Observable.js:45
    MapOperator.call @ map.js:54
    Observable.subscribe @ Observable.js:42
    CatchOperator.call @ catch.js:79
    Observable.subscribe @ Observable.js:42
    MapOperator.call @ map.js:54
    Observable.subscribe @ Observable.js:42
    CatchOperator.call @ catch.js:79
    Observable.subscribe @ Observable.js:42
    webpackJsonp.1241.InfoComponent.ngAfterViewInit @ info-json.component.ts:28
    callProviderLifecycles @ core.es5.js:11045
    callElementProvidersLifecycles @ core.es5.js:11020
    callLifecycleHooksChildrenFirst @ core.es5.js:11004
    checkAndUpdateView @ core.es5.js:12026
    callViewAction @ core.es5.js:12333
    execComponentViewsAction @ core.es5.js:12279
    checkAndUpdateView @ core.es5.js:12024
    callViewAction @ core.es5.js:12333
    execEmbeddedViewsAction @ core.es5.js:12305
    checkAndUpdateView @ core.es5.js:12019
    callViewAction @ core.es5.js:12333
    execComponentViewsAction @ core.es5.js:12279
    checkAndUpdateView @ core.es5.js:12024
    callViewAction @ core.es5.js:12333
    execEmbeddedViewsAction @ core.es5.js:12305
    checkAndUpdateView @ core.es5.js:12019
    callViewAction @ core.es5.js:12333
    execComponentViewsAction @ core.es5.js:12279
    checkAndUpdateView @ core.es5.js:12024
    callWithDebugContext @ core.es5.js:13006
    debugCheckAndUpdateView @ core.es5.js:12546
    ViewRef_.detectChanges @ core.es5.js:10115
    (anonymous) @ core.es5.js:5052
    ApplicationRef_.tick @ core.es5.js:5052
    (anonymous) @ core.es5.js:4932
    ZoneDelegate.invoke @ zone.js:365
    onInvoke @ core.es5.js:4125
    ZoneDelegate.invoke @ zone.js:364
    Zone.run @ zone.js:125
    NgZone.run @ core.es5.js:3994
    next @ core.es5.js:4932
    schedulerFn @ core.es5.js:3828
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:236
    SafeSubscriber.next @ Subscriber.js:185
    Subscriber._next @ Subscriber.js:125
    Subscriber.next @ Subscriber.js:89
    Subject.next @ Subject.js:55
    EventEmitter.emit @ core.es5.js:3814
    NgZone.checkStable @ core.es5.js:4090
    NgZone.setHasMicrotask @ core.es5.js:4174
    onHasTask @ core.es5.js:4137
    ZoneDelegate.hasTask @ zone.js:418
    ZoneDelegate._updateTaskCount @ zone.js:438
    Zone._updateTaskCount @ zone.js:262
    Zone.runTask @ zone.js:182
    drainMicroTaskQueue @ zone.js:591
    ZoneTask.invoke @ zone.js:464
    dashboard:1 XMLHttpRequest cannot load http://localhost:8080/assets/json/data.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 405.
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    According to latest error message

    Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 405.

    This is a cross origin request error. Do you get this error on development or production ?