在添加此服务之前,一切都运行良好。但是只要它被添加,即使它是空的,该组件只会呈现一个空白页面(并打破应用程序)。没有错误被抛出。 删除GuideService(以及save(),因为它依赖)使应用程序再次完美运行。我没有经验......感谢任何帮助!
创建-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));
}
}
答案 0 :(得分:1)
代码看起来正确。根据个人经验,确保您将app.module.ts文件中的服务作为提供者包含在内。请在此链接https://angular.io/guide/ngmodule
下查看服务提供商