繁体   English   中英

在Angular 6中从一个组件导航到另一个组件时,主题无法正常工作

[英]Subject is not working when route navigating from one component to another component in Angular 6

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

服务:

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

}

组件A将消息发送给可观察者

@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中触发subscription方法。请提出建议。

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

如果您使用的是Subject ,那么您只能获取订阅后发出的值。

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

主体与行为主体之间的差异

感谢您的想法@Amit。 我使用了ReplaySubject(1) ,它运行良好。

recipeSelected = new ReplaySubject<any>(1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM