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

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

本文关键字:组件 调用 另一个 一个 何包含 然后      更新时间:2023-09-26

所以我对AngularJS 2还是个新手,有一些问题我在网上找不到明确的答案。

我的第一个问题是如何在angular2应用程序中包含多个组件?这就是我目前的做法,但我认为我做得不对。此外,你能看看我是如何提供服务的吗?

引导程序.ts

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

应用

// 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?
  }
}

第二个组件.ts

// DEPENDENCIES GO HERE
@Component({
  selector: 'second-component'
})
@View({
  templateUrl: '/views/second.html'
})
export class Second {
  constructor() {
  }
  public callme() {
      return "I work!";
  }
}

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

最后,如何从app.ts文件调用第二个Component.ts文件中的"callme()"函数?

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

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

我感谢你的帮助。

干杯!

我的第一个问题是如何在angular2应用程序中包含多个组件?

// 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] 
})

关于如何注入CCD_ 1。它比这简单得多(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下看到它的一个示例。

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

通过directives属性包含组件绝对没有错,事实上就是这样做的,组件也是从指令扩展而来的。

最后,如何从app.ts文件调用第二个Component.ts文件中的"callme()"函数?

您只需查询应用程序的子

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();
  }
}

我建议你仔细阅读教程,因为你错过了上面提到的一些基本步骤。