英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论