angular - 如何获取来自角度服务的变量
问题描述
我有这个 create-movies 组件,它让我可以使用表单创建电影。
@Component({
selector: 'app-createMovie',
templateUrl: './createMovie.component.html',
styleUrls: ['./createMovie.component.css']
})
export class CreateMovieComponent{
constructor(public moviesService:MoviesService) { }
onMovieCreate(form:NgForm){
const movie:Movie = {
title:form.value.title,
file:form.value.file,
direction:form.value.direction,
year:form.value.year,
country:form.value.country,
duration:form.value.duration,
cast:{
name1:form.value.name1,
name2:form.value.name2
}
}
this.moviesService.addMovie(movie)
}
}
这个服务做一些事情,即将电影存储在一个数组中,然后由其他组件使用
@Injectable ({providedIn:"root"})
export class MoviesService{
private movies:Movie[] = [];
private moviesUpdated = new Subject<Movie[]>();
constructor() { }
addMovie(movie:Movie){
this.movies.push(movie)
this.moviesUpdated.next([...this.movies]);
}
getMoviesUpdateListener() {
return this.moviesUpdated.asObservable();
}
当我从另一个组件调用服务以显示创建的电影时,this.movies(HTML 中需要它)是空的。
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
moviesUpdated:Subscription;
movies:Movie[]=[];
constructor(public movieService: MoviesService){}
ngOnInit(){
this.moviesUpdated = this.movieService
.getMoviesUpdateListener()
.subscribe(
(moviesReturned:Movie[]) => {
this.movies=moviesReturned;
}
);
}
this.movies,里面 subscribe 被填充,但外面,它是 []。
需要电影数组的组件的 HTML 文件。
<div class="container">
<div class="row h-100 align-items-center">
<div class="col-2"></div>
<div class="col-8">
<form #classifyMovies="ngForm" (submit)=classifyEmotion(classifyMovies)>
<div>
<label for="chooseMovie" name="movie">Choose a <code>movie</code> or series</label>
<select class="form-control" [(ngModel)]=movie name="movie">
<option [value]="movie.title" *ngFor="let movie of movies">{{movie.title}}</option>
</select>
</div>
<div>
<label for="chooseEmotion" name="emotion">How did you <code>felt</code>?</label>
<select class="form-control" ngModel #emotion="ngModel" name="emotion">
<option [value]="emotion.emotion" *ngFor="let emotion of emotions">{{emotion.emotion}}</option>
</select>
</div>
<br>
<button class="btn btn-block btn-classify" type="submit">Classify Movie</button>
</form>
<br><br><br>
</div>
<div class="col-2"></div>
</div>
解决方案
它起作用了,使用 BehaviorSubject 而不是 Subject
private moviesUpdated = new BehaviorSubject<Movie[]>([]);
并实施
ngOnDestroy() {
this.moviesUpdated.unsubscribe();
}
我相信是因为 Behavior Subject 保存了最后一个值。
推荐阅读
- c# - 如何获得链接的 1-n 个元素的列表?
- html - 仅在物化 css 中为大屏幕显示静态广告空间
- keras - Google colaboratory, Keras:以 HDF5 文件格式保存模型并将其下载到笔记本电脑
- python - 如何在 Pandas Dataframe 中对两列进行分组并获取值计数后获取最高值行?
- python - 给定 3-dim 索引批次的 3-dim 数据批次的最后一个昏暗仅采用 n-length-subset 的 numpy 方式
- python - 通过与其他列表进行比较来计算列表中每个单词出现的相对频率
- r - 如何向堆叠的条形图添加点
- c# - var 如何处理数字?
- rest - 使用 Resteasy 上传文件时出现“没有这样的文件或目录”错误
- javascript - 重力有点像谷歌重力 - javascript,html