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

时间:2017-07-04 22:28:44

标签: javascript angular

我正在尝试将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?

3 个答案:

答案 0 :(得分:2)

将标题设为服务的公共属性,如下所示:

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

答案 1 :(得分:2)

title.service.ts中,您可以声明一个名为title的变量,并具有setter和getter:

title: string ="";

// replace fetchTitle with setTitle 
// remember to change it in the component too
setTitle(title) {
    this.title = title;
  }

getTitle() {
    return this.title;
  }

然后,当初始化ResultPage.component时,从getTitle()调用TitleService并将结果设置为组件中声明的变量。

以下是通过共享服务共享数据的example

答案 2 :(得分:0)

关注点分离...您的目标网页用于选择列表项并导航到结果页面。让它做到这一点,只有那样。让ResultPage.component完成剩下的工作。注意:其他答案建议在TitleService中存储最后一个标题的值。将状态存储在服务中并不是一个好主意。然后,TitleService不能用作将任何标题与当前导航分开的通用方法,没有副作用。

删除(点击)活动。将“show”添加为QueryParam。

landingpage.component.html

<li [routerLink]="['/details', list.id]" 
    [queryParams]="{show: list.show}" 
     *ngFor="let list of shows">
     {{list.show}}
</li>

订阅router params和queryparams以获取id和show。

resultpage.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '../../services/title.service';

@Component({
  ...
})
export class ResultPageComponent implements OnInit, OnDestroy {

 itemId: string;
 show: string;
 subParams: any;       // infinite Observable to be unsubscribed
 subQueryParams: any;  // infinite Observable to be unsubscribed

 constructor(
          ... 
          private TitleService: TitleService,
          protected route: ActivatedRoute,
          protected router: Router,
          ...
 ) {}

 ngOnInit() {
   this.subParams = this.route.params.subscribe(this.onParams);
   this.subQueryParams = this.route.queryParams(this.onQueryParams);
 }

 ngOnDestroy() {
   // Delete active subscribes on destroy
   this.subParams.unsubscribe();  
   this.subQueryParams.unsubscribe();  
 }

 onParams = (params: any) => {
   this.itemId = params['id'];
 }

 onQueryParams = (data: any) => {
  this.show = data.show;
  if(this.show) {
    this.TitleService.fetchTitle(this.show)
  }
 }