如何包含多个组件,然后可能从一个组件调用一个函数到另一个组件?

How to include multiple components and then potentially call a function from one to the other?

所以我对 AngularJS 2 还是很陌生,有几个问题我一直无法在网上找到明确的答案。

我的第一个问题是如何在您的 angular2 应用程序中包含多个组件?这就是我目前正在做的,但我相信我做错了。此外,您能看看我是如何添加服务的吗?

bootstrap.ts

// DEPENDENCIES GO HERE

bootstrap(App,[
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

app.ts

// DEPENDENCIES GO HERE

import {Socket} from './services/socket.ts'; // Socket.io Service
import {Second} from './pages/secondComponent.ts';

@Component({
  selector: 'main-component'
})
@View({
  templateUrl: '/views/template.html',
  directives: [Second]
})
@RouteConfig([
  new Route({path: '/', component: Home, as: 'Home'}),
  new Route({path: '/home', component: Home, as: 'Home'})
])
export class App {
  router: Router;
  location: Location;
  socket: Socket;

  constructor(router: Router, location: Location) {
    this.router = router;
    this.location = location;
    this.socket = new Socket(); // <-- Is this how to use a "service"? I'm sure this is wrong as I would need to create a new socket instance every time I wanted to use it? Singleton?
  }
}

secondComponent.ts

// DEPENDENCIES GO HERE

@Component({
  selector: 'second-component'
})
@View({
  templateUrl: '/views/second.html'
})
export class Second {
  constructor() {

  }
  public callme() {
      return "I work!";
  }

}

如果我将第二个组件作为指令包含在它加载的 app.ts 文件中的 @view 中,但我认为这是错误的,因为它是一个组件而不是指令。

最后,我将如何从 app.ts 文件调用 secondComponent.ts 文件中的 "callme()" 函数?

var second = new Second(); 
second.callme() 

有效,但不确定这是否正确,因为我认为它正在再次实例化组件??

感谢您的帮助。

干杯!

My first question is how does one include multiple components in your angular2 app?

// Note that @View is optional
// see https://github.com/angular/angular/pull/4566
@Component({
    directives : [Cmp1, Cmp2, Cmp3, Cmp4, CmpN] 
})

// Or
@Component({})
@View({
    directives : [Cmp1, Cmp2, Cmp3, Cmp4, CmpN] 
})

关于如何注入Services。它比那简单得多(angular2 为您创建实例,不需要 new ;) )

@Component({
  selector: 'main-component',
  providers : [Socket] // <-- Inject it into the component
})
export class App {
  socket: Socket;

  constructor(socketSvc: Socket) { // <-- Get the instance created above
    this.socket = socketSvc;
  }
}

您可以在 viewProviders 下查看示例。

If I include the second Component as a directive inside of the @view in the app.ts file it loads but I believe this is wrong as it's a component and not a directive.

通过 directives 属性 包含你的组件绝对没有错,事实上你就是这样做的, Components extends from Directives.

Lastly, how would I go about calling the "callme()" function in the secondComponent.ts file FROM the app.ts file?

您只需查询 App 的子项

export class App implements AfterViewInit {
  // Assuming you have only one 'Second' child, if you have multiple you must use @ViewChildren
  @ViewChild(Second) second: QueryList<Second>;

  afterViewInit() {
    this.second.callMe();
  }
}

我建议您完成 tutorial,您缺少其中提到的一些基本步骤。