首页 > 解决方案 > 在Angular 6中从一个组件导航到另一个组件时,主题不起作用

问题描述

我有组件 A、组件 B 和服务。我在服务中声明了主题并在组件 B 中订阅了主题,并且在导航到组件 B 之前,我正在将一些数据从组件 A 发送到主题。它正在导航到组件 B,但订阅方法没有触发。

服务:

@Injectable({
  providedIn: 'root'
})
export class ServiceTestService {
storage: Recipe;
recipeSelected = new Subject<any>();
constructor() { }

}

组件 A向 observable 发送消息

@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html'
 })

export class RecipeItemComponent implements OnInit {

@Input() recipe: Recipe;

  constructor(
     private recipeService: ServiceTestService,
     private rt: Router) { }

  ngOnInit() {
  }

  onRecipeSelected(name: number) {

this.recipeService.recipeSelected.next(this.recipe);
this.rt.navigate(['/recipe', this.ind]);

  }
}

组件 B: 这里我订阅了 Observable。

@Component({
  selector: 'app-recipe-detail',
  templateUrl: './recipe-detail.component.html',
  styleUrls: ['./recipe-detail.component.css']
  })

export class RecipeDetailComponent implements OnInit, OnDestroy {
  recipe: Recipe;

  constructor(private recipeService: ServiceTestService) { }

ngOnInit() {

this.recipeService.recipeSelected.subscribe(

  (res: any) => {
    console.log(`Recipe Component ${res}`); }
);

}

}

它正在从组件 A 导航到组件 B,但订阅方法未在组件 B 中触发。请建议。

标签: angularsubject

解决方案


改为使用BehaviorSubject,以便您始终获得在新订阅之前发出的当前值(最新)。

如果您正在使用Subject,那么您只会获得订阅后发出的值。

export class ServiceTestService {
   storage: Recipe;
   recipeSelected = new BehaviorSubject<any>();
   constructor() { }
}

主题和行为主题之间的区别


推荐阅读