I am using Angular 5 and I’ve created a service using the angular-cli
What I want to do is to create a service that reads a local json file for Angular 5.
This is what I have … I’m a bit stuck…
JavaScript
x
20
20
1
import { Injectable } from '@angular/core';
2
import { HttpClientModule } from '@angular/common/http';
3
4
@Injectable()
5
export class AppSettingsService {
6
7
constructor(private http: HttpClientModule) {
8
var obj;
9
this.getJSON().subscribe(data => obj=data, error => console.log(error));
10
}
11
12
public getJSON(): Observable<any> {
13
return this.http.get("./assets/mydata.json")
14
.map((res:any) => res.json())
15
.catch((error:any) => console.log(error));
16
17
}
18
19
}
20
How can I get this finished?
Advertisement
Answer
First You have to inject HttpClient
and Not HttpClientModule
,
second thing you have to remove .map((res:any) => res.json())
you won’t need it any more because the new HttpClient
will give you the body of the response by default , finally make sure that you import HttpClientModule
in your AppModule
:
JavaScript
1
17
17
1
import { HttpClient } from '@angular/common/http';
2
import { Observable } from 'rxjs';
3
4
@Injectable()
5
export class AppSettingsService {
6
7
constructor(private http: HttpClient) {
8
this.getJSON().subscribe(data => {
9
console.log(data);
10
});
11
}
12
13
public getJSON(): Observable<any> {
14
return this.http.get("./assets/mydata.json");
15
}
16
}
17
to add this to your Component:
JavaScript
1
17
17
1
@Component({
2
selector: 'mycmp',
3
templateUrl: 'my.component.html',
4
styleUrls: ['my.component.css']
5
})
6
export class MyComponent implements OnInit {
7
constructor(
8
private appSettingsService : AppSettingsService
9
) { }
10
11
ngOnInit(){
12
this.appSettingsService.getJSON().subscribe(data => {
13
console.log(data);
14
});
15
}
16
}
17