如何从子组件中访问父组件中注入的服务

huangapple go评论50阅读模式
英文:

How to access an injected service in parent component from child

问题

在子组件中,您可以通过继承 ParentComponent 来访问和使用 Http 对象。由于子组件继承自父组件,它会继承父组件中的字段和属性,包括 Http 对象。您可以像在父组件中一样在子组件中访问和使用 Http 对象,无需额外的配置或操作。

英文:

Consider the following code to be in ParentComponent.razor:

@inject HttpClient Http
<h1>Parent</h1>
@code{
    protected override async Task OnInitializedAsync()
    {
        Http.DefaultRequestHeaders.Add("test", "true");
    }
}

and ChildComponent.razor:

@inherits ParentComponent
<h1>Child</h1>
@code{
    
}

How can I access and use Http object in the child component?

答案1

得分: 2

You need to inject the service from @code to make it accessible for inheriting components.

<h1>Parent</h1>
@code{
    [Inject]
    public HttpClient Http { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        Http.DefaultRequestHeaders.Add("test", "true");
    }
}

Use base to access it.

@inherits ParentComponent
<h1>Child</h1>
@code{
    private void DoSomething(){
       System.Uri baseAddress = base.Http.BaseAddress;
    }
}
英文:

You need to inject the service from @code to make it accessible for inheriting components.

<h1>Parent</h1>
@code{
    [Inject]
    public HttpClient Http { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        Http.DefaultRequestHeaders.Add("test", "true");
    }
}

Use base to access it.

@inherits ParentComponent
<h1>Child</h1>
@code{
    private void DoSomething(){
       System.Uri baseAddress = base.Http.BaseAddress;
    }
}

huangapple
  • 本文由 发表于 2023年2月8日 20:29:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定