【发布时间】:2018-05-08 09:03:30
【问题描述】:
我的情况:
我有一个显示图块的组件,每个图块代表一个数组中的一个对象,该数组使用 ngfor 循环。 单击磁贴时,我想将对象传递给不同的组件,该组件负责在可修改的字段中显示该对象的所有属性。
我尝试过的:
在做了一些研究并遇到多篇文章向我展示如何为父子层次结构实现这一点以及一些解释有必要使用共享服务以实现所需功能后,我决定尝试并设置这样的服务。
但是,我似乎没有得到什么时候应该导航到不同的路线。似乎导航找到位置很早,因为在详细组件中检索传递给服务的对象时未定义。
我的代码:
显示图块的组件具有以下功能,可将点击的对象传递给共享服务:
editPropertyDetails(property: Property) {
console.log('Edit property called');
return new Promise(resolve => {
this.sharedPropertyService.setPropertyToDisplay(property);
resolve();
}).then(
() => this.router.navigate(['/properties/detail'])
)
}
共享服务具有设置属性对象和检索属性对象的功能,如下所示:
@Injectable()
export class SharedPropertyService {
// Observable
public propertyToDisplay = new Subject<Property>();
constructor( private router: Router) {}
setPropertyToDisplay(property: Property) {
console.log('setPropertyToDisplay called');
this.propertyToDisplay.next(property);
}
getPropertyToDisplay(): Observable<Property> {
console.log('getPropertyToDisplay called');
return this.propertyToDisplay.asObservable();
}
}
最后是必须接收被点击对象但得到一个未定义对象的细节组件:
export class PropertyDetailComponent implements OnDestroy {
property: Property;
subscription: Subscription;
constructor(private sharedPropertyService: SharedPropertyService) {
this.subscription = this.sharedPropertyService.getPropertyToDisplay()
.subscribe(
property => { this.property = property; console.log('Detail Component: ' + property.description);}
);
}
ngOnDestroy() {
// When view destroyed, clear the subscription to prevent memory leaks
this.subscription.unsubscribe();
}
}
提前致谢!
【问题讨论】:
-
如果你可以在 stackblitz 中复制它,我很难弄清楚它会更容易理解。截至目前,对shared services 的解释更简单
-
您需要在包含您的两个组件的模块中提供共享服务。是这样吗?否则它不会是一个单例,并且服务会失去它的目的
-
是的,该服务在功能模块的提供者中列出。
-
您找到其他解决方案了吗?
-
@RobertWilliams 我在下面发布了我的解决方案。看看接受的答案。
标签: angular angular-components angular-router