[英]Subject is not working when route navigating from one component to another component in Angular 6
I have Component A, Component B, and a service. 我有组件A,组件B和服务。 I declared Subject in the service and subscribed the Subject in component B., And I'm sending some data from Component A to the Subject before navigating to component B. It is navigating to component B, but the Subscribe method is not triggering.
我在服务中声明了Subject,并在组件B中订阅了Subject。在导航到组件B之前,我正在从组件A向主题发送一些数据。它正在导航到组件B,但没有触发Subscribe方法。
Service:
服务:
@Injectable({
providedIn: 'root'
})
export class ServiceTestService {
storage: Recipe;
recipeSelected = new Subject<any>();
constructor() { }
}
Component A Sending the message to observable
组件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]);
}
}
Component B: Here I subscribed the Observable.
组件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}`); }
);
}
}
It's navigating from Component A to Component B but the subscribe method is not triggering in Component B. Please suggest. 它正在从组件A导航到组件B,但没有在组件B中触发subscription方法。请提出建议。
Use BehaviorSubject
instead, so that you always get the current value (latest) that was emitted before the new subscription. 请改用
BehaviorSubject
,以便始终获得在新订阅之前发出的当前值(最新)。
If you are using Subject
, then you only get values that are emitted after subscription. 如果您使用的是
Subject
,那么您只能获取订阅后发出的值。
export class ServiceTestService {
storage: Recipe;
recipeSelected = new BehaviorSubject<any>();
constructor() { }
}
Thanks for the Idea @Amit. 感谢您的想法@Amit。 I used
ReplaySubject(1)
and it is working perfectly. 我使用了
ReplaySubject(1)
,它运行良好。
recipeSelected = new ReplaySubject<any>(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.