本文介绍了如何在Angular中访问未初始化的组件的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何使用Ionic Framework教程模板访问Angular中组件的属性.它似乎尚未初始化,因为我试图将其打印到控制台.这是app.component.ts中的代码:

 导出类MyApp {@ViewChild(Nav)导航:导航;页面:数组< {title:字符串,徽章:数字,component:任何}> ;;构造函数(公共平台:平台,公共菜单:MenuController,public statusBar:StatusBar,public splashScreen:SplashScreen,公共authService:AuthService,公共loadingCtrl:LoadingController,私人toastCtrl:ToastController){this.initializeApp();//设置我们的应用页面this.pages = [{title:'Series',badge:0,component:SeriesDetailPage},{title:'Borrow',badge:0,component:BorrowViewPage},{title:'Request',badge:0,component:RequestViewPage},{title:'Borrow List',badge:0,component:BorrowListPage},{标题:请求列表",徽章:0,组件:RequestListPage},{title:'Setting',badge:0,component:SettingPage}];varrowerPage = this.pages.find(page => page.title ===借阅");console.log((borrowPage.component as BorrowViewPage).items);//打印未定义this.nav.setRoot(BorrowViewPage);}...openPage(page){//单击菜单中的链接时关闭菜单this.menu.close();//如果不是当前页面,请导航到新页面this.nav.setRoot(page.component);} 

这是BorrowViewPage组件的代码:

 导出类BorrowViewPage {公共项目:借入[];构造函数(公共navCtrl:NavController,公共authService:AuthService,公共navParams:NavParams){this.view();//进行HTTP调用以初始化项目数组}} 

目前似乎没有一个组件调用其构造函数.如果是这样,是否可以手动调用组件构造函数?

添加:神奇的是,我不知道类实例的来源.这是应用程序从app.module.ts开始的地方:

  @NgModule({声明:[MyApp,SettingPage,SeriesDetailPage,SeriesListPage,BorrowListPage,BorrowViewPage,RequestListPage,RequestViewPage],进口:[BrowserModule,HttpModule,IonicModule.forRoot(MyApp),],引导程序:[IonicApp],entryComponents:[MyApp,SettingPage,SeriesDetailPage,SeriesListPage,BorrowListPage,BorrowViewPage,RequestListPage,RequestViewPage],提供者:[状态栏,开机画面{提供:ErrorHandler,useClass:IonicErrorHandler},验证服务]})导出类AppModule {} 

通过将根页面设置为app.component.ts中所需的任何页面,将调用该组件名称的构造函数.我认为构造函数会被调用吗?没有把握.单击app.html中指定的任何按钮时,其工作方式相同:

 < ion-menu [content] ="content">< ion-header>< ion-toolbar>< ion-title> MyApp</ion-title></ion-toolbar></ion-header>< ion-content>< ion-list>< button ion-item * ngFor =让页面数"(click)="openPage(p)">{{p.title}}< ng-container * ngIf ="p.badge!= 0">< span class ="badge badge-assertive"> {{p.badge}}</span></ng-container></button></ion-list></ion-content></ion-menu>< ion-nav [root] ="rootPage" #content swipeBackEnabled ="false"></ion-nav> 

在这种情况下,我什至如何检索该类实例?

解决方案

在这里更新我的答案,因为我意识到自己刚刚得出结论(由于您进行了异步调用,因此数据尚不可用,因此结果为未定义")

现在,当我仔细观察时,我意识到您正在尝试做的事情(从父范围(MyApp)访问子组件的数据(BorrowViewPage)/属性)不是常规的,也不是Angular希望您这样做的:

将http调用移至提供程序并让组件调用/订阅它们也是一种更好的做法.因此,我认为您可以通过这种方式实现更简洁的实施.

如果您有理由仍然希望使用当前的方法来实现目标,并且不适合使用规范的方法(共享服务),请分享这些原因.

I can't figure out how to access properties of a component in Angular using Ionic Framework Tutorial template. It seems to be uninitialized, because I tried to print it out to the console. Here is the code in app.component.ts:

export class MyApp {
  @ViewChild(Nav) nav: Nav;

  pages: Array<{title: string, badge: number, component: any}>;

  constructor(
    public platform: Platform,
    public menu: MenuController,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen,
    public authService: AuthService,
    public loadingCtrl: LoadingController,
    private toastCtrl: ToastController
  ) {
   this.initializeApp();

   // set our app's pages
   this.pages = [
     { title: 'Series', badge: 0, component: SeriesDetailPage },
     { title: 'Borrow', badge: 0, component: BorrowViewPage },
     { title: 'Request', badge: 0, component: RequestViewPage },
     { title: 'Borrow List', badge: 0, component: BorrowListPage },
     { title: 'Request List', badge: 0, component: RequestListPage },
     { title: 'Setting', badge: 0, component: SettingPage }
   ];

   var borrowPage = this.pages.find(page => page.title === 'Borrow');
   console.log((borrowPage.component as BorrowViewPage).items); //Print undefined
   this.nav.setRoot(BorrowViewPage);
  }
  ...
  openPage(page) {
    // close the menu when clicking a link from the menu
    this.menu.close();
    // navigate to the new page if it is not the current page
    this.nav.setRoot(page.component);
  }

Here is the code for BorrowViewPage component:

export class BorrowViewPage {
  public items: Borrow[];

  constructor(public navCtrl: NavController, public authService: AuthService, public navParams: NavParams) {
    this.view(); //Make a HTTP call to initialize items array
  }
}

It seems that none of the components have its constructor called at this point. If so, is it possible to call the component constructor manually?

ADDED: What magical is that I don't know where the class instance even comes from. Here is where the app starts at app.module.ts:

@NgModule({
  declarations: [
    MyApp,
    SettingPage,
    SeriesDetailPage,
    SeriesListPage,
    BorrowListPage,
    BorrowViewPage,
    RequestListPage,
    RequestViewPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    SettingPage,
    SeriesDetailPage,
    SeriesListPage,
    BorrowListPage,
    BorrowViewPage,
    RequestListPage,
    RequestViewPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    AuthService
  ]
})
export class AppModule {}

By setting the root page to any page you want in app.component.ts, the constructor of that component name get called. I think the constructor is called then?! Not sure. It works in the same way when I click on any of the buttons specified in app.html:

<ion-menu [content]="content">

  <ion-header>
    <ion-toolbar>
      <ion-title>MyApp</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content>
    <ion-list>
      <button ion-item *ngFor="let p of pages" (click)="openPage(p)">
        {{p.title}}
        <ng-container *ngIf="p.badge != 0">
            <span class="badge badge-assertive">{{p.badge}}</span>
        </ng-container>
      </button>
    </ion-list>
  </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

How do I even retrieve that class instance in this case?

解决方案

Updating my answer here as I realized I just jumped into conclusion (that because you have async call the data is not yet available and hence result is 'undefined').

Now as I looked closer I realize that what you are trying to do (access child's component (BorrowViewPage) data/property from parent scope (MyApp)) is not conventional and is not how Angular wants you to do it: https://angular.io/guide/component-interaction#component-interaction

I think in your use case you should consider this interaction model:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Rationale here is that in your case both components (MyApp and BorrowViewPage) require to access same data which ideally should be available at a "foundation" or "shared" service.

Service should be initialized and imported/injected into each of the components and this way you are getting cleaner design:

It is also a better practice to move your http calls to a provider and have components call / subscribe to them. So I think you can get cleaner implementation this way.

If you have a reason why you still want to achieve something with your current approach and that the canonical approach (shared service) is not suitable - please share those reasons.

这篇关于如何在Angular中访问未初始化的组件的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:48