Everything was working perfectly before adding this service. But as soon as it's added, even if it's empty, the component just renders a blank page (and breaks the app). No errors are thrown. Removing GuideService (and save() since it's dependent) makes the app work perfectly again. I'm inexperienced... any help is appreciated!
create-guide.component.ts
import { GuideService } from '../guide/guide.service';
import { Component, OnInit } from '@angular/core';
import { Guide } from '../guide/guide.model';
import { Form, FormArray, FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-create-guide',
templateUrl: './create-guide.component.html',
styleUrls: ['./create-guide.component.css']
})
export class CreateGuideComponent implements OnInit {
rform: FormGroup;
constructor(private fb: FormBuilder, public guideService: GuideService) {
}
save(model: Form) {
console.log(model);
const newGuide = new Guide('', '', '', [], '');
this.guideService.addGuide(newGuide)
.subscribe(
data => console.log(data),
error => console.error(error)
);
}
ngOnInit() {
this.rform = this.fb.group({
title : ['', Validators.compose([Validators.required])],
description : ['', Validators.compose([Validators.required])],
prereqs: ['', Validators.compose([Validators.required])],
experienceLevel: ['', Validators.required],
guideResources: this.fb.array([
this.initGuideResource()
])
});
}
initGuideResource() {
return this.fb.group({
resourceTitle: [null, Validators.compose([Validators.required])],
resourceLink: [null, Validators.compose([Validators.required])],
resourceTime: [null, Validators.compose([Validators.required])],
resourceContent: [null, Validators.compose([Validators.required])]
});
}
addGuideResource() {
// add guide to the list
const control = <FormArray>this.rform.controls['guideResources'];
control.push(this.initGuideResource());
}
removeGuideResource(i: number) {
// remove guide from the list
const control = <FormArray>this.rform.controls['guideResources'];
control.removeAt(i);
}
}
guide.service.ts
import { Guide } from './guide.model';
import { Headers, Http, Response } from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class GuideService {
constructor(private http: Http) {}
addGuide(guide: Guide) {
const body = JSON.stringify(guide);
const headers = new Headers({'Content-Type': 'application/json'});
return this.http.post('http://localhost:3000/create', body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json));
}
}
The code looks correct. From personal experience, make sure your including the service in your app.module.ts file as a provider. Look under service providers in this link https://angular.io/guide/ngmodule