微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

typescript – 与router-outlet的Angular2组件通信

要么我没有得到模式,要么我的设计是错误的.

使用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中遇到的错误就是这个……

EXCEPTION:无法解析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现在可以作为应用程序级服务添加到您的引导程序中,然后可以传递到您希望与之共享的所有路由中.
dependency-injection-in-angular-2

bootstrap(App,UserSettingsService,{ 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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐