如何在两个组件之间共享数据?

How to share data between two component?

我正在使用 angular 4,我无法与 component.I 有 sidenav 组件进行通信,我想将值边栏共享到主要组件。 谢谢。

有很多方法。例如:

- @Output/@Input
- Service

事实上,Angular 文档中甚至有一整节专门介绍它:

https://angular.io/guide/component-interaction

您可以创建服务并将其添加到应用程序级别 (root) 的提供程序,这样服务将可用于注入所有组件,并且对此服务的任何更改都将持续存在。

@Injectable()
export class GlobalSharedService {
  public data:any;
}

app.module

@NgModule({
  ....
  providers: [GlobalSharedService]
})
export class AppModule { }

In Angular 6 you can add the service to proviers at the app.module level like this

@Injectable({
  providedIn: 'root',
})
export class GlobalSharedService {
   public data:any;
  }

All service added at the app.module the created once that why the persist there state and called singleton service

sidenav.component.ts
passData:any

sidenav.component.html
//Call your main component & share passData property
<app-component [passData]="passData"></app-component>

main.component.ts
@ViewChild(passData) passData: SidenavComponent;