我有组件 A、组件 B 和一项服务。我在服务中声明了 Subject 并订阅了组件 B. 中的主题,并且在导航到组件 B 之前,我将一些数据从组件 A 发送到主题。它正在导航到组件 B,但没有触发订阅方法。
服务:
@Injectable({
providedIn: 'root'
})
export class ServiceTestService {
storage: Recipe;
recipeSelected = new Subject<any>();
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
组件 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]);
}
}
Run Code Online (Sandbox Code Playgroud)
组件 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}`); }
);
}
}
Run Code Online (Sandbox Code Playgroud)
它正在从组件 A 导航到组件 B,但订阅方法未在组件 B 中触发。请提出建议。
BehaviorSubject改为使用,以便您始终获得在新订阅之前发出的当前值(最新)。
如果您正在使用Subject,那么您只能获得订阅后发出的值。
export class ServiceTestService {
storage: Recipe;
recipeSelected = new BehaviorSubject<any>();
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1024 次 |
| 最近记录: |