我有组件A,组件B和服务。我在服务中声明了Subject,并在组件B中订阅了Subject。在导航到组件B之前,我正在从组件A向主题发送一些数据。它正在导航到组件B,但是Subscribe方法未触发。 / p>
服务:
@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中触发。请提出建议。
答案 0 :(得分:3)
请改用BehaviorSubject
,以便始终获得在新订阅之前发出的当前值(最新)。
如果您使用的是Subject
,则只能获取订阅后发出的值。
export class ServiceTestService {
storage: Recipe;
recipeSelected = new BehaviorSubject<any>();
constructor() { }
}
答案 1 :(得分:1)
感谢Idea @Amit。我使用了ReplaySubject(1)
,它运行良好。
recipeSelected = new ReplaySubject<any>(1);