我没有得到图案,或者我的设计错误。
使用angular2-beta0,打字稿
基本上,我已经建立了一个非常基本的应用程序,它的根组件是一个控制主视图的路由器,然后在某些页面上,我有一个子路由器来控制该组件上的子视图。
我似乎在苦苦挣扎的是如何通过组件之间的通信来构造事物。就目前的应用而言,它的排列方式对我来说是合乎逻辑的,主要路线的视图没有共同点,在子路线视图中,它们都共享相同的侧面导航和标题。我所遇到的问题似乎正在传达给子视图的父视图。似乎是一个孩子在路由器出口中,它无法获得父组件的依赖关系。我看过自定义事件,但是这些事件似乎仅在绑定到模板时才起作用。唯一的其他选择似乎是服务,但是这对我来说似乎很困难,因为理想情况下,我希望父组件控制子组件的状态。
任何示例代码如何...
@Component({
selector: 'app'
})
@View({
template: '<router-outlet></router-outlet>',
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/', as: 'Login', component: LoginForm },
{ path: '/main/...', as: 'Main', component: Main}
])
class App {
constructor(private _router: Router) {
}
}
bootstrap(App, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, { useValue: '/' })]);
@Component({
selector: 'main'
})
@View({
templateUrl: '/client/main/main.html',
directives: [ROUTER_DIRECTIVES, NgClass, Menu, Main]
})
@RouteConfig([
{ path: '/', as: 'Clear', component: StateClear },
{ path: '/offer', as: 'Offer', component: StateOffer }
])
export class Main {
constructor(private _router: Router) {
}
}
@Component({
selector: 'state-clear'
})
@View({
templateUrl: '/client/bookings/state-clear.html'
})
export class StateClear {
constructor(main: Main) {
}
}
我在DI中遇到的错误是...
例外:无法解析StateClear(未定义)的所有参数。确保它们都具有有效的类型或注释。
事件没有错误,因为我看不到如何在模板之外进行监听。
因此,您可能想做的就是将DI与父组件一起使用。
就像您在这里做的那样:
export class StateClear {
constructor(main: Main) {
}
}
您可能只想创建一个服务来处理要在路径/组件级别共享的数据。
@Injectable()
export class UserSettingsService {
// Application wide settings/config should be instatiated here
// with a call from OnInit we can set all of these values.
constructor() { }
public iId: number;
public userName: string;
public isLoggedIn: boolean;
public firstName: string;
public lastName: string;
public permissions: string[];
getUser(userName:string) {
// with an AJAX request get user Auth.
return Promise.resolve(api.getUserAuth(userName));
}
}
现在可以将此UserSettingsService作为应用程序级服务添加到您的引导程序中,然后可以将其传递到您要与其共享的所有路由中。Angular-Injection-in-Angular-2
bootstrap(App, [ROUTER_PROVIDERS, UserSettingsService, provide(APP_BASE_HREF, { useValue: '/' })]);
然后,执行以下操作以访问组件中的数据。
@Component({
selector: 'state-clear'
})
@View({
templateUrl: '/client/bookings/state-clear.html'
})
export class StateClear {
userName:string;
userId:int;
isLoggedIn:boolean;
constructor(private _userSettings: UserSettingsService) {
// Not that you would do this here again but just for an example that the data is retrievable here.
this.userName = this._userSettings.userName;
this.userId = this._userSettings.iId;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句