gpt4 book ai didi

javascript - 用于将数据传递到组件到组件的 Angular 2 共享服务

转载 作者:行者123 更新时间:2023-11-30 09:33:33 25 4
gpt4 key购买 nike

我正在尝试将 this.title 的字符串值从我的 LandingPage.component 传递到我的 ResultPage.component。

我检索了 list.show 值,并将它发送到我的 TitleService 中,如下所示:

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;
}
}

下面是我如何管理我的路由:

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)

如何将我的 title 值从我的服务发送到我的 ResultPage.component?

最佳答案

像这样使标题成为服务的公共(public)属性:

// 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.
}
}

然后任何其他组件都可以注入(inject)此服务并访问 this.titleService.selectedTitle

关于javascript - 用于将数据传递到组件到组件的 Angular 2 共享服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44914707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com