I want to find help with Angular 5 and its module httpClient, before posting I look several times the doc of angular and various tutorial without success.
I'm trying to pass two informations in a form from a json from a server I created locally.
What I want: Pass my information on my page from the HttpClient component.
The encountered difficulties
I have two errors, my first attempts, I correctly recover the JSON file but in my console, I have a 404 error (I specify my server is on and I can see my json at the address I have provided in my component-service.ts).
My second error since Friday:
Cross-Origin Request Blocking: The "Same Origin" policy does not allow viewing of the remote resource located at http: // localhost: 3000 / main.json. Reason: The CORS header "Access-Control-Allow-Origin" is missing.
I added a Headers object with the 'Access-Control-Allow-origin': '*' property. Angular does not want to know anything, worse looking at the log, he does not show me anything in the header he returns to me…
main-service.ts
import { Injectable, OnInit} from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Main } from '../model/main';
const baseUri = 'http://localhost:3000/';
const jsonDirectory = 'javascripts/';
const main = 'main.json';
const jsonHeaders = new HttpHeaders({'Content-type': 'application/json', 'Access-Control-Allow-Origin': '*'});
@Injectable()
export class MainService implements OnInit {
mainRequest = baseUri + jsonDirectory + main;
jsonOption = jsonHeaders;
constructor(private http: HttpClient) { }
ngOnInit() {
console.log(this.getMain());
}
getMain(): Observable<Main> {
return this.http.get<Main>(this.mainRequest, {withCredentials: true, headers: this.jsonOption});
}
}
main.component.ts
import {Component, Injectable, OnInit} from '@angular/core';
import { MainService } from '../shared/service/main-service';
import { FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {map} from 'rxjs/operators';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
@Injectable()
public id: number;
public name: string;
constructor(private mainService: MainService, private fb: FormBuilder) { }
mainGroup = this.fb.group({
id: [{value: '', disabled: true}, Validators.min(0)],
name: ['', Validators.minLength(3)]
});
ngOnInit() {
this.getMain();
}
getMain() {
this.mainService.getMain()
.subscribe(data => {this.id = data.id; this.name = data.name; }, err => console.log(err));
}
confirmForm() {
console.log(this.mainGroup);
}
}