【问题标题】:Binding to Input Properties of Child Component within Router Outlet绑定到路由器插座中子组件的输入属性
【发布时间】:2017-01-24 02:21:54
【问题描述】:

我想将父组件输入 element 值绑定到子组件属性。皱纹是子组件通过路由器插座嵌套在父组件中。似乎最好的方法是在父组件和子组件之间使用共享服务,如 here 所示。

这是我的测试实现:

父组件:

import { Component } from '@angular/core';
import { Router }   from '@angular/router';
import { ThreadsService }   from './threads.service';

@Component({
    moduleId: module.id,
    selector: 'threads',
    templateUrl: 'threads.component.html',
    styleUrls: ['threads.component.css'],
    providers: [ ThreadsService ]
})


export class ThreadsComponent {

    constructor(private router: Router,
    private threadsService: ThreadsService){}

    emit(value: string) {
        let emission = value;
        this.threadsService.emissionReceived(emission);

    }

}

父模板

<div class="col-sm-9 threads">
    <div class="threads">
        <div class="thread-container">
            <ul class="nav nav-tabs">
                <li [class.active]="router.url == '/featured'">
                    <a routerLink="/featured">Featured</a>
                </li>
                <li [class.active]="router.url == '/new'">
                    <a routerLink="/new">New</a>
                </li>
                <li [class.active]="router.url == '/trending'">
                     <a routerLink="/trending">Trending</a>
                </li>
                <div class="col-sm-3 search-div">
                    <input #threadsearch (keyup.enter)="emit(threadsearch.value)" type="text" class="form-control  search-box" placeholder="Search topics...">
                </div>
            </ul>
            <!--Child component in here-->          
            <router-outlet></router-outlet> 
        </div>
    </div>
</div>

子组件:

import { Component, Input } from '@angular/core';
import { ThreadsService } from './threads.service'
import { Subscription }   from 'rxjs/Subscription';

@Component({
    moduleId: module.id,
    selector: 'featured-threads',
    template: `
        <div class="featured">
        <thread [threads]="threads" [emission]="emission"></thread>
        </div>`, 
    providers: [ ThreadsService ]
})

export class FeaturedThreadsComponent {
    subscription: Subscription;
    emission = '';

    constructor(private threadsService: ThreadsService) { 
        this.subscription = threadsService.searchResults$.subscribe(
            emission => {
                this.emission = emission;
                console.log(emission)
            }
        )

    ngOnDestroy() {
    // prevent memory leak when component destroyed
        this.subscription.unsubscribe();

    }
}

我可以将emission 从父组件和共享服务登录到控制台,但不能从这个子组件登录。如您所见,子组件有自己的子组件,emission 最终将在其中呈现的模板。

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    首先

    providers: [ ThreadsService ]
    

    您的所有代码都在为Child component 创建新实例以及为Parent 创建新实例,这将对您的代码造成损害。因为服务必须是单例的,必须在NgModule中添加

    例如

    import { NgModule }           from '@angular/core';
    import { BrowserModule }      from '@angular/platform-browser';
    import { AppComponent }       from './app.component';
    
    import { ThreadsService }        from './threads.service';
    
    import { FormsModule }        from '@angular/forms';
    
    @NgModule({
      imports: [ BrowserModule,  FormsModule ],
      declarations: [AppComponent],
      providers: [ ThreadsService ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }
    

    【讨论】:

    • 根据documentation,这个provides the instance of the service that it shares with its children (through the providers metadata array) and injects that instance into itself through its constructor。孩子also injects the service in its constructor。我的理解是,只要您不打算将该组件注入组件树之外,您就可以在组件的元数据数组中提供服务。
    • @J.AdamConnor 您会为每个提供者获得一个实例。如果您在两个组件上提供它,将为这些组件的每个实例创建一个实例。如果您仅在父级上提供它,则子级将获得父级(或任何祖先)的实例注入。因此,只在包含路由器插座的组件上提供一次(对于它的祖先之一)。树的顶部(根注入器)是AppModule。当在任何祖先组件上都没有找到提供者时,将咨询根注入器。
    【解决方案2】:

    Günther 的评论完全正确:

    “您会为每个提供者获得一个实例。如果您在两个组件上提供它,将为这些组件的每个实例创建一个实例。如果您仅在父级上提供它,那么子级将获得父级的实例(或任何祖先)注入。因此,只在包含路由器出口的组件上提供一次(对于它的祖先之一)。在树的顶部(根注入器)是 AppModule。当在任何祖先组件上找不到提供程序时,根注入器咨询”

    您可以在ngModule 中提供服务:

    providers: [ ThreadsService ]
    

    因此从您的孩子和父母中删除提供者。

    或者你从你的子组件中删除提供者。

    这是您的代码的一个 plunker,其中 providers 仅在父级中设置:

    plunker

    查看控制台时,您可以看到数据现在也发送给了子节点。

    最后是angular.io的一些节选:

    当底部的组件请求依赖项时,Angular 会尝试使用在该组件自己的注入器中注册的提供程序来满足该依赖项。如果组件的注入器缺少提供程序,它会将请求传递给其父组件的注入器。如果该注入器不能满足请求,它将把它传递给它的父组件的注入器。请求不断冒泡,直到我们找到可以处理请求或用完组件祖先的注入器。如果我们的祖先用完了,Angular 会抛出一个错误。

    ...假设我们为 Car、Engine 和 Tires 配置了根注入器(标记为 A)。我们创建了一个子组件 (B),它为 Car 和 Engine 定义了自己的提供者。这个子组件是另一个组件 (C) 的父级,该组件定义了自己的 Car 提供者。

    在幕后,每个组件设置自己的注入器,并为该组件本身定义一个或多个提供程序。

    【讨论】:

    • 哈!当我的孩子的 providers 数组中没有 ThreadsService 时,我一直在想为什么还要继续讨论这个问题。事实证明我做到了,但没有意识到。我很抱歉,伙计们。我知道它不应该在那里,所以我认为它不是!接受您的回答,因为它清楚地指出该数组存在于我的孩子中。
    • :D 不用担心,众所周知,当涉及到您自己的代码时,我们都会失明:D
    • 不确定是否可以为 cmets 简洁地回答这个问题,但我对这个示例的行为有一个后续问题。如果我从这样的服务this.searchResultsSource.subscribe(emission =&gt; console.log(emission)) 将排放记录到控制台,就会发生一些奇怪的事情。这是log。第一次搜索不记录任何内容。第二,搜索字段中的值。第三次记录值两次,第四次记录三次,依此类推......知道为什么吗?
    • 嗯...不确定...你在哪里做这个日志记录?
    • 在threads.service方法emmisionReceived()中。 emissionReceived(value: string) { this.searchResultsSource.next(value); this.searchResultsSource.subscribe(emission =&gt; console.log(emission)) }
    猜你喜欢
    • 2016-08-02
    • 2017-04-29
    • 2017-07-02
    • 1970-01-01
    • 2018-07-28
    • 2021-03-13
    • 2017-02-15
    • 1970-01-01
    • 2017-03-24
    相关资源
    最近更新 更多