所以,我对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文件中的@视图中,那么它将加载,但我认为这是错误的,因为它是一个组件,而不是一个指令。
最后,如何从secondComponent.ts文件调用app.ts文件中的"callme()“函数?
var second = new Second();
second.callme()
工作,但不确定这是否正确,因为我认为它再次实例化了组件?
谢谢你的帮助。
干杯!
发布于 2015-11-04 04:06:47
我的第一个问题是,如何在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]
})
关于如何注入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
下看到一个例子。
如果我将第二个组件作为指令包含在app.ts文件中的@视图中,那么它将加载,但我认为这是错误的,因为它是一个组件,而不是一个指令。
通过directives
属性包含组件绝对没有什么问题,事实上,这就是您如何做到的,也是组件从指令扩展。
最后,如何从secondComponent.ts文件调用app.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();
}
}
我建议您通过教程,您错过了上面提到的一些基本步骤。
https://stackoverflow.com/questions/33518237
复制相似问题