Angular 如何从爱奥尼亚的其他页面访问app.component变量和方法?

Angular 如何从爱奥尼亚的其他页面访问app.component变量和方法?,angular,typescript,ionic-framework,ionic3,Angular,Typescript,Ionic Framework,Ionic3,我想访问和更改其他页面(otherpage.ts)或其他组件的app.component.ts变量或访问方法,例如 应用程序组件.ts @Component({ templateUrl: 'app.html' }) export class MyApp { accessedVariable: any; constructor(){ } accessedMethod() { ..something } } @Component({ selector: 'pa

我想访问和更改其他页面(
otherpage.ts
)或其他组件的
app.component.ts
变量或访问方法,例如

应用程序组件.ts

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  accessedVariable: any;

  constructor(){ }

  accessedMethod() {
   ..something
  }

}
@Component({
  selector: 'page-other',
  templateUrl: './otherpage.html',
})
export class OtherPage {

  constructor() { }
}
otherpage.ts

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  accessedVariable: any;

  constructor(){ }

  accessedMethod() {
   ..something
  }

}
@Component({
  selector: 'page-other',
  templateUrl: './otherpage.html',
})
export class OtherPage {

  constructor() { }
}

18-02-2020

请不要使用
事件发射器
。使用可观察的
模式。否则,您将不得不在更新到时面临问题。i、 e.
Ionic 5
上没有事件API

原创

您可以通过多种方式来实现这一点

我可以告诉你的一个方法是使用

Events是一个发布-订阅样式的事件系统,用于发送和 响应应用程序中的应用程序级事件


另一种方法可能是使用
提供程序
。在该用例中,您可以通过
提供程序
共享您的
方法
变量
。最快的方法是使用GlobalVars提供程序:

首先使用以下工具安装它:

ionic g provider globalvars
这将自动将新提供商添加到您的app.module.ts文件中

import {Injectable} from '@angular/core';
@Injectable()
export class GlobalVars { 
myGlobalVar: any;
constructor() { 
this.myGlobalVar = ""; 
} 

setMyGlobalVar(value) { 
this.myGlobalVar = value; 
}

getMyGlobalVar() { 
return this.myGlobalVar; 
} 
}
您在那里定义了gettersetter方法,并且可以通过此类的实例访问所需的变量!在YourOtherPage.ts中,您可以使用以下内容获取变量:this.glVars.getMyGlobalVar()


在这里您可以阅读更多信息:

我的使用案例Ionic 5电容器:我想在头组件的ion头中显示ion spinner。在header组件中,我订阅了可观察变量,我可以在另一个服务中将其设置为true。这种方法很灵活,我可以在子组件或父组件/页面中使用它

MyService.service.ts:(初始化可观察变量并设置方法)

另一个service.service.ts:

export class AnotherService {

    constructor(private myService: MyService) {}

    public someMethod() {    
        this.myService.spinner = true;
    }
}
MyComponent.component.ts:

export class MyComponent implements OnInit {
    public showSpinner: boolean;

    constructor(private myService: MyService) {}

    ngOnInit() {
        this.myService.obSpinner.subscribe(showSpinner => {
          this.showSpinner = showSpinner;
        });
      }
}
MyComponent.component.html:

<ion-spinner *ngIf="showSpinner"></ion-spinner>


OtherPage
MyApp
的孩子吗?@Dr.Geek你能简单解释一下你想做什么,特别是访问方法吗。另外,app.component和其他页面父级是否相关或完全独立?这可能会有所帮助。若你们只是想改变子页面中的菜单内容,只需使用它不是我想要的。我想访问app.component.ts意味着我想从子页面或其他页面更改某个变量。例如,
,是否可以在更改子页面时更改ion内容菜单……您可以使用
事件
,正如我在
1st
方法中提到的那样。你为什么不能用那种方法?根据您的用例,这是您在此处拥有的唯一选项。因为如果第一次加载项目,app.ccomponent(以及菜单项)项目页面已加载且发生更改后,我们无法更改现有app.component.ts中的参数…希望您能使用特定用例更新您的问题。此时,您只需提出一个一般性问题。i、 如何访问方法和变量。我会先尝试你的答案,然后我可以更改它不是我想要的。我想访问app.component.ts!我知道我也试过了,但是页面是用离子型/角型封装的。您可以尝试使用jquery和index.html在页面上触发。我这样做是为了我的媒体数据库