Angular 2共享服务可将数据传递到组件之间 [英] Angular 2 shared service to pass data to component-to-component
问题描述
我正在尝试将this.title
的字符串值从LandingPage.component传递给ResultPage.component.
I am trying to pass the string value of this.title
from my LandingPage.component to my ResultPage.component.
我检索list.show
值,并将其发送到我的TitleService
中,如下所示:
I retrieve the list.show
value, and send it to my TitleService
in like so in my:
landingpage.component.html
<ol>
<li (click)="selectShow(list.show)" [routerLink]="['/details', list.id]" *ngFor="let list of shows">{{list.show}}
</li>
</ol>
landingpage.component.ts
import { TitleService } from '../../services/title.service';
constructor(private TitleService: TitleService) {}
selectShow(show) {
this.TitleService.fetchTitle(show)
}
以上将list.show
值发送给我:
title.service.ts
// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
fetchTitle(title) {
console.log("title is " + title); // this outputs correctly
return title;
}
}
这是我在自己的办公室中管理路由的方式:
And here is how I manage the routing in my:
app-routing.module.ts
import { TitleService } from './services/title.service';
const routes: Routes = [
{ path: '', component: LandingPage },
{
path: 'details/:id', component: ResultPage
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [TitleService]
})
我的问题
一旦我在服务组件中收到title.show
值,就不确定如何将其发送到接收组件( resultpage.component )
Once I receive the title.show
value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)
如何将我的title
值从服务发送到ResultPage.component?
How can I send my title
value from my service to my ResultPage.component?
推荐答案
将标题设为服务的公共属性,如下所示:
Make the title a public property of the service like this:
// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
selectedTitle: string;
fetchTitle(title) {
console.log("title is " + title); // this outputs correctly
this.selectedTitle = title;
return title; // No need to return it.
}
}
然后其他任何组件都可以注入此服务并访问this.titleService.selectedTitle
Then any other component can inject this service and access this.titleService.selectedTitle
这篇关于Angular 2共享服务可将数据传递到组件之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!