我在通知组件时出现问题,发生了更改。
假设我有一个组件A,它发出事件E(通过一些服务)。组件B订阅了该事件。如果我在console.log中收到组件B的事件和属性,我确实看到它已被更改。
但是,组件的模板保持不变。
我想如果我使用ChangeDetectorRef和changeDetectorRef.detectChanges()
,则会刷新视图。
但我不断收到以下错误:
Attempt to use a destroyed view: detectChanges
。
这是否需要使用和通知组件?还有更好的东西吗?
以下是我正在使用的代码的简短示例:
这是组件B,应该更改
import {Component, OnInit, ChangeDetectorRef} from '@angular/core';
import {LiveIndexService} from './services/live-index.service';
import {LiveNavigationService} from '../../services/live-navigation.service';
@Component({
selector: 'live-index',
template: require('./index.html'),
providers: [BetradarService]
})
@CanActivate(() => {
return areDependenciesFetched();
})
export class LiveIndexComponent implements OnInit {
constructor(
private _liveNavigationService: LiveNavigationService,
private _changeDetector: ChangeDetectorRef) {}
public ngOnInit() {
this._liveNavigationService.sportSelectedEvent$.subscribe(selectedSport => {
this._selectedSport = selectedSport;
console.log(this._selectedSport); // I see it is changed, but if I omit next line, it's not working.
this._changeDetector.detectChanges();
});
} }
这是触发发出事件的服务的组件A
import {Component, Output, EventEmitter, ChangeDetectorRef} from 'angular2/core';
import {LiveNavigationService} from '../../services/live-navigation.service';
@Component({
selector: 'live-breadcrumbs',
template: require('./live-breadcrumbs.html')
})
export class LiveBreadcrumbsComponent {
private _selectedSport;
public constructor(private _liveNavigationService: LiveNavigationService,
private _changeDetectorRef: ChangeDetectorRef) {}
// this function is triggered from template (onClick)
private _selectSport(sport) {
this._selectedSport = sport;
this._router.navigate(['Index']); // this will navigate to component B
this._liveNavigationService.selectSport(sport);
}
}
我从服务中发出对象:
import {Injectable, EventEmitter} from '@angular/core';
@Injectable()
export class LiveNavigationService {
public sportSelectedEvent$: EventEmitter<any> = new EventEmitter<any>();
public selectSport(sport) {
this.sportSelectedEvent$.emit(sport);
}
}
这是html
<div id="breadcrumb">
<div class="dropdown">
<div class="wrapper">
<a class="name">{{ _selectedSport ? _selectedSport.name : 'Sport'}}</a>
<div class="icon"><span></span></div>
</div>
<div class="list">
<div class="title">Sports</div>
<div class="list-item" [ngClass]="{selected: sport == _selectedSport}" (click)="_selectSport(sport)" *ngFor="let sport of _sportsWithMatches">{{ sport.name }}</div>
</div>
</div>
我还在RC1上。
答案 0 :(得分:1)
我认为您不应该使用changeDetectorRef
。由于change detection strategy未设置为onpush
我想如果你在导航完成后移动发射逻辑,那么你的代码就可以了。
如果您使用的是rc1路由器
this._router.navigate(['Index']).then( ()=>this._liveNavigationService.selectSport(sport);)
对于3.0.0路由器,您可以
this._router.events.subscribe( e =>
{
if(e instance of NavigationEnd && this.router.url == 'index')
this._liveNavigationService.selectSport(sport);})