在 AngularDart 中,我有一个看法。
https://angulardart.org/tutorial/08-ch06-view.html
'demo_table': ngRoute(
path: '/demo/table',
view: 'views/demotable.html'
),
在 View 上,我有两个组件。
<component1 view-string="Component 1"></component1>
<component2 view-string="Component 2"></component1>
我希望 view-string 是一个可以由 component1 或 component2 更改的字符串的实例。更改应反射(reflect)在组件中字符串的显示中。
我看不到如何在此 View 中保留字符串,因为此 View 不是组件。如果这个 View 真的是一个带有 Dart 对象的组件,我通常会在 View 字符串中使用“{{someString}}”。
最佳答案
解决问题并仍然使用组件而不是 Controller 的一种方法是引入一个包含共享数据的类。事实上,这也与 Controller 完全相同,但这是一个有争议的问题,因为 Controller 似乎正如 Randal 所提到的那样正在消失。
(请原谅任何错别字或错误 - 我正在文本编辑器中输入,所以这可能无法编译。)
第一步:引入一个共享类,将其注解为 Injectable:
@Injectable()
class MySharedClass
{
String mySharedVariable;
}
第二步:确保 Angular 可以通过告诉 Angular 来注入(inject)该类:
class MyInitModule extends Module {
MyInitModule() {
// Your bindings ...
// Your components, controllers are bound for Angular's DI
// This is the important part:
bind(MySharedClass);
// Typical Angular.Dart bindings:
bind(RouteInitializerFn, toValue: yourRouteInitializer);
bind(NgRoutingUsePushState, toFactory: (_) =>
new NgRoutingUsePushState.value(false));
}
main() {
applicationFactory().addModule(new MyInitModule()).run();
}
第三步:现在将共享类添加到组件的构造函数中。只要你声明了一个实例,Angular 就会自动注入(inject)一个实例:
@Component(
selector: 'componentA',
templateUrl: 'correct_path', // insert correct value here.
publishAs: 'cmp')
class ComponentA {
MySharedClass sharedClass;
ComponentA(this.sharedClass) {
}
@Component(
selector: 'componentB',
templateUrl: 'correct_path', // insert correct value here.
publishAs: 'cmp')
class ComponentB {
MySharedClass sharedClass;
ComponentB(this.sharedClass) {
}
现在,您可以根据需要访问两个(或更多)组件之间的共享类。
(根据 Wilson Yeung 修改以添加 Injectable() 注释)
关于dart - 如果两个不同的组件在同一个 View 中(ngRoute),它们如何共享一个公共(public)对象或通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096221/