简体   繁体   English

Angular 2共享服务可将数据传递到组件之间

[英]Angular 2 shared service to pass data to component-to-component

I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component. 我试图将this.title的字符串值从我的LandingPage.component传递给ResultPage.component。

I retrieve the list.show value, and send it to my TitleService in like so in my: 我检索list.show值,并将其发送到我的TitleService中,如下所示:

landingpage.component.html 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 landingpage.component.ts

import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}

The above sends the list.show value to my: 上面将list.show值发送给我:

title.service.ts 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 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]
})

My question 我的问题

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.show值后,我不确定如何将其发送到接收组件( resultpage.component

How can I send my title value from my service to my ResultPage.component? 如何将我的title值从服务发送到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.
  }
}

Then any other component can inject this service and access this.titleService.selectedTitle 然后,其他任何组件都可以注入此服务并访问this.titleService.selectedTitle

In title.service.ts you can declare a variable called title and have setter and getter: 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;
  }

Then, when ResultPage.component is initialized, call getTitle() from TitleService and set the result to a variable declared in the component. 然后,在初始化ResultPage.component时,从TitleService调用getTitle()并将结果设置为组件中声明的变量。

Here's an example of sharing data via shared services. 这是通过共享服务共享数据的示例

Separation of concerns... Your landing page is used to select the list item and navigate to the result page. 关注点分离...您的登录页面用于选择列表项并导航到结果页面。 Let it do just that and only that. 让它做到这一点,只有做到这一点。 Let the ResultPage.component do the rest. 让ResultPage.component完成其余的工作。 Note: Other answers recommend storing the value of the last title in the TitleService. 注意:其他答案建议将最后一个标题的值存储在TitleService中。 It's not a good idea to store state in a service. 将状态存储在服务中不是一个好主意。 Then TitleService cannot be used as a generic way to get any title separate from your current navigation, without side effects. 然后,TitleService不能用作获取与当前导航分开的任何标题的通用方法,而没有副作用。

Remove (click) event. 删除(单击)事件。 Add 'show' as a QueryParam. 将“显示”添加为QueryParam。

landingpage.component.html landingpage.component.html

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

Subscribe to router params and queryparams to get the id and show. 订阅路由器参数和queryparams以获取ID并显示。

resultpage.component.ts 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)
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM