typescript - Angular 在数据库中加载 Json 文件
我有一个 JSON 文件需要加载到数据库中,但当我想添加该对象时,会出现此错误
无法读取未定义的属性 'post'
这是 Movie 组件中的代码:
loadJSONFile() {
this.dataService.loadJsonFile().subscribe(
data => data.forEach(function(movie: Movie){
DataService.prototype.addMovie(movie).subscribe();
})
)
}
当我尝试这段代码时:
this.dataService.loadJsonFile().subscribe(
data => this.filteredMovies = data
)
console.log("filteredMovies length "+this.filteredMovies.length);
for (var i=0; i < this.filteredMovies.length;i++){
console.log(this.filteredMovies[i]);
this.dataService.addMovie(this.filteredMovies[i]).subscribe(
movie => console.log(movie)
);
}
数据库中没有任何变化,因为代码继续执行它的行,而 observable 在从 filteredMovies 获取数据时还没有完成
这是数据服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Movie } from './model/movie.model'
@Injectable()
export class DataService {
baseUrl: string ='http://localhost:8089/library/movie/';
constructor(private http:HttpClient) { }
addMovie(movie: Movie){
return this.http.post(this.baseUrl, movie);
}
loadJsonFile() {
return this.http.get<Movie[]>("./assets/movies.json");
}
}
有人可以帮帮我吗?
答案#1
我明白了!!谢谢 @user184994,我做了一些研究,发现 this 在嵌套函数内部会丢失上下文,所以为了防止这种情况,我们需要使用 bind()
bind() 创建了该函数的新版本,当调用时,this 值已经被设置。注意,我们需要对每个嵌套函数使用 .bind(this)。
这是解决方案:
this.dataService.loadJsonFile().subscribe(
data => data.forEach(function(movie: Movie){
this.dataService.addMovie(movie).subscribe();
}.bind(this), this.filteredMovies = data
)
你可以在这篇文章中找到,它解释得很好:当“this”失去上下文时该怎么办
