首页 > 解决方案 > 如何获取来自角度服务的变量

问题描述

我有这个 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.movi​​es(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.movi​​es,里面 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>

标签: angularobservable

解决方案


它起作用了,使用 BehaviorSubject 而不是 Subject

  private moviesUpdated = new BehaviorSubject<Movie[]>([]);

并实施

  ngOnDestroy() {
    this.moviesUpdated.unsubscribe();
  }

我相信是因为 Behavior Subject 保存了最后一个值。


推荐阅读