我有组件 A、组件 B 和服务。我在服务中声明了Subject并在组件B中订阅了Subject,并且在导航到组件B之前我将一些数据从组件A发送到Subject。它正在导航到组件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 中触发。请提出建议。
Use BehaviorSubject
相反,这样您始终可以获得新订阅之前发出的当前值(最新)。
如果您正在使用Subject
,那么您只能获得订阅后发出的值。
export class ServiceTestService {
storage: Recipe;
recipeSelected = new BehaviorSubject<any>();
constructor() { }
}
主体和行为主体之间的区别 https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)