【问题标题】:Implementing methods from an Angular 4 service in two different components在两个不同的组件中实现来自 Angular 4 服务的方法
【发布时间】:2017-07-05 21:35:24
【问题描述】:

我在 2 个差异组件中使用了一项服务:一个在分页按钮上,第二个在侧边栏中。这两个组件处于同一级别。 问题是按钮组件上的方法有效,但如果我在侧边栏上使用它们就不起作用。

服务

public navigate(action: string) {
 if (typeof this.ACTIONS[action] === 'undefined')
 return;

 let shift = this.ACTIONS[action];
 this.setCurrent(shift);

 const curr = this.getCurrent();
 this.activeIndex = curr.index;
 return this.router.navigate([curr.name]);
}

public setDisableFirst() {
 const curr = this.getCurrent();
 if(curr.index == 0) {
  return true;
 }
}

public setDisableLast() {
 const curr = this.getCurrent();
 return ((curr.index + 1) == (this._pages.length)) ? true : false;
}

public setActiveIndex() {
 const curr = this.getCurrent();
 return 'done-' + curr.index;

}

按钮

 public disableFirst() {
  return this.PrevNextService.setDisableFirst();
 }

 public disableLast() {
  return this.PrevNextService.setDisableLast();
 }

 <button type="button" (click)="navigate('PREV')" [disabled]="disableFirst()">
 <button type="button" (click)="navigate('NEXT')" [disabled]="disableLast()">

侧边栏

 public activeClasss() { 
  return this.PrevNextService.setActiveIndex();
 }


 <div class="list-group-wrapper"  [ngClass]="activeClasss()">

如果我在以下方法中控制台登录服务 const curr = this.getCurrent();:navigate、setDisableFirst、setDisableLast,当我单击下一步或从按钮返回时,我会得到准确的页码(1、2、3 等)组件。

Service 的最后一个方法 setActiveIndex 使用与上述方法相同的变量。在这里,在服务中,如果控制台日志const curr = this.getCurrent(); 我只得到我现在的第一(1)页。如果我继续单击下一个或上一个按钮,则此 const 保持不变(1)。

我使用 Angular 4。有人可以告诉我为什么会出现这种行为吗?

【问题讨论】:

  • 你的this.getCurrent() 方法是什么样的?
  • 给我我所在的实际页面。在构造函数中我有this._current = this._pages.find((page) =&gt; { return this.router.url === page.name; });,然后我声明了函数:public getCurrent() { return this._current; }
  • _pages.find() 有什么作用?请提供更多相关代码。
  • _pages 是一个数组,使用 find 检查 url 是否与 _pages 数组中的页面名称相同。给我一些类似的东西:{name: "../page1", index: 0}
  • 如需帮助,请提供更多相关代码。

标签: angular


【解决方案1】:

您是如何注册服务的?你有它在你的一个模块的提供者数组中吗?类似于下面显示的ProductService

您是否在多个模块中注册了它?还是在组件中?

要使服务作为单例正常工作,它的提供者只需要通过提供者数组在一个地方注册,如下所示。

@NgModule({
  imports: [
    SharedModule
    ])
  ],
  declarations: [
    ProductListComponent
  ],
  providers: [
    ProductService
  ]
})
export class ProductModule {}

【讨论】:

  • 侧边栏 @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.scss'], providers: [PrevNextService] }) 和按钮 @Component({ selector: 'app-trade-buttons', templateUrl: './trade-btn.component.html', styleUrls: ['./trade-btn.component.scss'], providers: [PrevNextService] }) ,两个组件使用相同的服务 PrevNextService。我在 prividers 上的 app.module 中有它
  • 你说得对,黛博拉。因为我在具有相同服务的每个组件中使用了 providers 数组,所以在每个 comp 中都是一个 diff 实例。因此,为了在所有组件中拥有相同的实例,我只在 app.module 中的提供程序中添加了它。
猜你喜欢
  • 1970-01-01
  • 2017-10-12
  • 2019-03-30
  • 2018-12-04
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多