angular - 通过 <router-outlet> 进行组件通信

标签 angular

我有一个根组件,它有一个不断变化的 bool 值,我想订阅那个不断变化的 bool 值,我的 <router-outlet> 中有一个组件。 .我知道我需要使用某种共享的双向服务。但是,共享服务的文档对我来说意义不大。 (我想我无法理解宇航员的例子)here ,任何帮助将不胜感激,这里有一些代码来展示我正在尝试做的事情。

根组件

@Component({
   selector: 'my-app',
   template: `<nav [state]="boolshow"  (show)="changeValue($event)" ></nav> 
          <article><router-outlet></router-outlet></article>  <-----component in router here
          <footer></footer>
          <h3>toggle state: {{boolshow}}</h3>`,
   styleUrls: ['./Css/app.css'],

   })
 export class AppComponent {
   boolshow: boolean;      <-----boolean that needs to be read
  }

最佳答案

这正是他们在 Angular2 Docs 中所说的:

  • 使用 Observable 创建服务

  • 在两个组件中注入(inject)相同的服务

  • 从一个组件将数据更新到服务

  • 从服务中读取数据的其他组件

例如

服务:

@Injectable()
export class DataService {
    private dataObs$ = new Subject();

    getData() {
        return this.dataObs$;
    }

    updateData(data: boolean) {
        this.dataObs$.next(data);
    }
}

组件:

@Component({
  selector: 'my-app',
  template: `<div (click)="updateData(false)">Click t oupdate Data FALSE</div>
             <div (click)="updateData(true)">Click to update Data TRUE</div>
            <child></child>
            `
})
export class AppComponent {
    constructor(private dataService: DataService) {}

    updateData(value: boolean) {
      this.dataService.updateData(value);
    }
}


@Component({
  selector: 'child',
  template: `<div><p>data from Service HERE:</p><p style="color:red"> {{myData}}</p></div>`
})
export class ChildComponent {
    myData: boolean;

    constructor(private dataService: DataService) {}

    ngOnInit() {
      this.dataService.getData().subscribe(data => {
        this.myData = data;
      })
    }
}

确保在组件中注入(inject)相同的服务(单例):

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent, ChildComponent ],
  providers: [ DataService ],
  bootstrap:    [ AppComponent ]
})

可以找到一个完整的工作示例 HERE : http://plnkr.co/edit/nJVC36y5TIGoXEfTkIp9?p=preview

PS:这就是 Angular2 中通过服务进行通信的方式,无论您的组件是否位于通过路由器的路由器 socket 内,它都可以在任何地方工作。

关于angular - 通过 <router-outlet> 进行组件通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834286/

相关文章:

angular - 如何在 Nx monorepo 中为 NestJS 和 Angular 之间共享的 API 接口(interface)启用 Swagger?

node.js - 为什么数据没有完整发送到mongodb数据库?

angular - 在表单外以 Angular 调用表单的提交按钮

javascript - Angular CLI 和 Angular Universal 无法使用 --prod 在服务器上使 environment.production 为真

Angular 4 - Http 到 HttpClient - 对象类型上不存在属性 'someproperty'

angular - 非法使用过滤器 typescript

angular - Ionic 2 angular-moment-timezone - 无法重新声明 block 范围变量 'tz'

javascript - 如何在 Javascript 中将字符串数组转换为特定的树结构

angular - 为什么我应该在简单的对象配置上使用 Angular 的依赖注入(inject)?

angular - 为什么当我单击使用 routerLink 和 queryParams 构建的链接时没有任何反应?