大佬教程收集整理的这篇文章主要介绍了angular – 从服务触发组件视图的更新 – 没有ChangeDetectorRef的提供者,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的一个服务注入了ChangeDetectorRef。编译工作正常,但是当引导应用程序时,我在浏览器中收到错误:没有ChangeDetectorRef的提供程序!
我以为我需要将它添加到我的AppModule中,但我找不到任何表明它在我可以导入的模块中的文档。我尝试将类本身添加到导入数组,但这导致了错误。尝试将其添加到模块中的providers数组时,我也遇到了错误。这是我的服务的简化版本:
import {Injectable,ChangeDetectorRef } from '@angular/core'; @Injectable() export class Myservice { private count: number = 0; constructor(private ref: ChangeDetectorRef){} increment() { this.count++; this.ref.detectChanges(); }
和app模块:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { Myservice } from './my.service'; @NgModule({ imports: [ BrowserModule ],declarations: [ AppComponent ],providers: [ Myservice ],booststrap: [ AppComponent ] }) export AppModule {}
我已经尝试删除我对ChangeDetectorRef的使用,我仍然遇到同样的问题。我猜我更新我的System JS配置有什么问题。
我最初使用angular-cli创建了应用程序,并且因为没有更新它而试图自己更新Angular。随着Angular 2.0.0的最终版本,他们更新了angular-cli以使用最新版本的angular。所以我将尝试使用他们的升级程序,希望这会更好。
更新2
webpack / angular-cli更新进展顺利。我现在使用Angular 2.0.0和angular-cli 1.0.0-beta14构建应用程序。我仍然在浏览器中得到相同的错误。我尝试从服务中删除ChangeDetectorRef,但我没有。我有两个服务。如果我从两个服务中删除它,那么我的应用程序加载正常,并且运行良好,除了我尝试使用ChangeDetectorRef。一旦我将其添加回其中一个文件,浏览器就会抱怨无法为其找到提供商。
我尝试在我的模块中导入它,但它不是一个模块,所以转换器抱怨。我尝试在我的模块中列出它是一个提供者,但它没有提供属性,所以转换器抱怨。如果我尝试将它放在声明数组中的类似问题。
在你的情况下,最好使用ApplicationRef:
import {Injectable,ApplicationRef } from '@angular/core'; @Injectable() export class Myservice { private count: number = 0; constructor(private ref: ApplicationRef) {} increment() { this.count++; this.ref.tick(); } }
我用Observables检查了这个解决方案,它没有任何问题:
import { ApplicationRef,Injectable } from '@angular/core'; import { Observable,replaySubject } from "rxjs/Rx"; import * as childProcess from 'child_process'; @Injectable() export class Reader { private output: replaySubject<String> = new replaySubject<String>(0); constructor(private ref: ApplicationRef) { var readerProcess = childProcess.spawn('some-process'); readerProcess.stdout.on('data',(data) => { this.output.next(data.toString()); this.ref.tick(); }); } public getOutput():Observable<String> { return this.output; } }
这是一个使用它的组件:
import {Component} from '@angular/core'; import { replaySubject,Observable } from "rxjs/Rx"; import { Reader } from './reader/reader.service'; @Component({ SELEctor: 'app',template: ` output: <div>{{output}}</div> ` }) export class App { public output: String; constructor(private reader: Reader) {} ngOnInit () { this.reader.getOutput().subscribe((val : String) => { this.output = val; }); } }
以上是大佬教程为你收集整理的angular – 从服务触发组件视图的更新 – 没有ChangeDetectorRef的提供者全部内容,希望文章能够帮你解决angular – 从服务触发组件视图的更新 – 没有ChangeDetectorRef的提供者所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。