【问题标题】:Can not update view on angular4 by component intraction through service无法通过服务通过组件交互更新角度 4 中的视图
【发布时间】:2018-03-01 06:16:29
【问题描述】:

您好,我正在尝试从组件(HeaderComponent)调用另一个组件(ProductComponent)的方法。为此,我使用了一项服务。我创建了一个服务 ProductService,它是这些组件之间的共享服务。但是当变量值在服务中更改时我不会更新视图请帮助。这是代码

productservice.service.ts

  import { Injectable, ChangeDetectorRef } from '@angular/core';
  import { Observable } from 'rxjs';
  import { Subject }    from 'rxjs/Subject';
  @Injectable()
  export class ProductServiceService {

    contentSource = new Subject();
    str = 'initial';
    content$ = this.contentSource.asObservable();
    constructor(private cdRef:ChangeDetectorRef) { }
    setData(str){
      this.str = str;
      console.log(str);
      this.cdRef.detectChanges();
    }
    getData(){
      return this.str;
    }

  }

header.component.ts

    @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
  providers: [ProductsComponent, ProductServiceService],
  changeDetection: ChangeDetectionStrategy.Default
})
export class HeaderComponent implements OnInit{

 constructor(public dialog: MdDialog,private _http: Http,  private cdRef:ChangeDetectorRef, private sharedService: ProductServiceService) 
 {
}    
ngOnInit() {
}
    newProudutsData(slug: string){
    this.sharedService.contentSource.next("echo");
    this.sharedService.setData('Done Calling');
    this.cdRef.detectChanges();
    }
}

product.component.ts

@Component({
    selector: 'app-products',
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.css'],
    changeDetection: ChangeDetectionStrategy.Default,
    providers: [ProductServiceService],
})
export class ProductsComponent implements OnDestroy {
    slug='';
    subscription: Subscription;
    testdata = 'abcd';
    constructor(private _http: Http, private sharedService: ProductServiceService) 
    {
            this.testdata = sharedService.getData();
            console.log("received222");
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

页面加载时我得到的最终输出是初始的,但是当方法 调用 newProudutsData() 应将其更改为 Done Calling。

-----已编辑--------

product组件定义在header组件中,路由时调用prodcut组件

{
            path: 'products/:id',
            component: ProductsComponent
 },

被调用。

【问题讨论】:

  • 显示 ./products.component.html 代码
  • 和 ./products.component.html

标签: angular angular-services


【解决方案1】:

组件有自己的服务,它们没有连接。您应该将服务提取到模块。当您为组件指定服务时,您仅将其设置为该组件的本地服务,这意味着您有 2 个不同的服务实例而不是一个,并且它们彼此不共享数据。我建议在 chrome deb 工具中使用 augury 来查看依赖注入

  @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit{

}

 @Component({
    selector: 'app-products',
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnDestroy {
}

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [ProductsComponent , HeaderComponent  ]
  providers: [
     ProductServiceService
  ]
})
export class YourModule {}

使用behaviorSubject代替主题

    contentSource = new BehaviorSubject('');

Subject 不会保存之前的值 BehaviorSubject 会。 如果 source 发出一些东西,但你当时没有订阅,你将失去这个值。

created Plunker

【讨论】:

  • 服务在 providers 数组中的app.module.ts 中定义。我试图从两个组件中删除它们,但没有任何效果
  • @NaveenSingh 好的。他们是父母和孩子。那么你需要使用的不是 Subject 而是 behaviorSubject
  • 当类别改变时,函数 newProudutsData() 被调用,然后调用 setData 服务方法 setData 设置变量值,但在 productComponent 中,变量值在构造函数中被调用(getData),但构造函数只是在页面加载时首先调用。但是当我在产品页面上并更改类别时,它没有得到反映,因为构造函数没有被称为任何解决方案。
  • @NaveenSingh 我将创建 plunker。因为你搞砸了很多
  • 已解决plnkr.co/edit/LwIPB52seD25PINErekY?p=info 仍然调用了一次构造函数,但每次 url 更改时都会调用 ngOnInit 方法,因此我更改了该事件的变量值。它与我之前尝试的工作流程不同,但我达到了最终结果。谢谢。
猜你喜欢
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多