【发布时间】:2017-08-13 10:09:07
【问题描述】:
以上是我在运行代码时在开发者工具的控制台部分发现的错误消息。页面按预期正常工作,但仍然弹出错误消息,这很奇怪。我尝试了很多方法来识别问题,但仍然不走运。请提供一些解决此问题的建议,谢谢。我的显示错误的 HTML 代码如下:
<!doctype html>
<html>
<body>
<div class="container">
<h1>Movie</h1>
<form (ngSubmit)="onSubmit()" #movieForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" required [(ngModel)]="model.title" name="title">
</div>
<button type="submit" class="btn btn-success" [disabled]="!movieForm.form.valid" >Save</button>
</form>
</div>
</body>
</html>
Angular 组件脚本如下:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OnInit } from '@angular/core';
import { Movie } from './movie';
@Component({
selector: 'movie-form',
templateUrl: './movie-form.component.html'
})
export class MovieFormComponent implements OnInit{
model: Movie;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('http://localhost:3000/api/movie').subscribe(data => {
this.model = new Movie( data['title']);
});
}
submitted = false;
onSubmit(){
this.submitted = true;
this.http.post('http://localhost:3000/api/movie', {
"title": this.model.title
}).subscribe(data => {
});
}
}
【问题讨论】:
-
在 TS 中声明
model = new Movie()。无论如何,您需要初始化model,以便在响应到达之前它不会是undefined:)