MY OWN SOLUTION
I created a new component
called test
in this folder:
I also created a mock called test.json
in the assests
folder created by angular cli
(important):
This mock looks like this:
[
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
In the controller of my component test
import
follow rxjs
like this
import 'rxjs/add/operator/map'
This is important, because you have to map
your response
from the http get
call, so you get a json
and can loop it in your ngFor
. Here is my code how I load the mock data. I used http
get
and called my path to the mock with this path this.http.get("/assets/mock/test/test.json")
. After this i map
the response and subscribe
it. Then I assign it to my variable items
and loop it with ngFor
in my template
. I also export the type. Here is my whole controller code:
import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'
export type Item = { id: number, name: string };
@Component({
selector: "test",
templateUrl: "./test.component.html",
styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
items: Array<Item>;
constructor(private http: Http) {}
ngOnInit() {
this.http
.get("/assets/mock/test/test.json")
.map(data => data.json() as Array<Item>)
.subscribe(data => {
this.items = data;
console.log(data);
});
}
}
And my loop in it's template
:
<div *ngFor="let item of items">
{{item.name}}
</div>
It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json
. Notice that you have also to import the HTTP
and Response
in your controller. The same in you app.module.ts (main) like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
HttpModule,
JsonpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }