angular - 在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 中触发。请建议。
解决方案
改为使用BehaviorSubject
,以便您始终获得在新订阅之前发出的当前值(最新)。
如果您正在使用Subject
,那么您只会获得订阅后发出的值。
export class ServiceTestService {
storage: Recipe;
recipeSelected = new BehaviorSubject<any>();
constructor() { }
}
推荐阅读
- sql - 带有一个额外的自定义条件列的 Oracle 查询
- mysql - MySQL左连接中的语法问题
- python-3.x - None appereance in a if statment
- python - 在 selenium 中使用“webdriver.Chrome()”时出错
- python - 将文本字符串转换为数据框 - 逗号分隔
- c# - 如何使用 ML.Net 执行具有许多特征的二元分类
- lua - 如果条件不满足,则在 Lua 上中断 while 循环
- angular - 如何将 ngbCarousel 箭头从图像中移开
- vue.js - 如何通过单击另一个 vue 组件中包含的按钮来获取 vue 组件的内容(模态窗口)?
- java - 使用“+”运算符的非字符串操作数后,结果字符串会进入字符串池吗?