Angular 2服务在儿童组件中不充当单例(可能的重复)



第二个更新

我的问题是在服务本身中,更改箭头功能解决问题的方法。


这可能是重复的,但是我对Angular DI进行了详尽的研究,很明显,在根级别注射服务使它们可以作为相同的实例可用于应用程序中的所有组件。

在我的AppComponent下方,我有三个孩子屏幕截图,确认并预览。我从屏幕截图组件中调用服务并在该服务上保存一些数据,然后尝试以后从预览组件上访问该数据,但似乎我正在访问该服务的新实例。

app.module

@NgModule({
  declarations: [
    AppComponent,
    Screenshot,
    Confirm,
    Preview,
  ],
  entryComponents: [
    Preview
  ],
  imports: [
    CommonModule,
    BrowserModule
  ],
  providers: [
    MessageService,
    ScreenshotService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnChanges, OnDestroy {
    @ViewChild(Preview) preview: Preview; 
    title: string;
    confirmed: boolean;
    constructor(
        private screenshotService: ScreenshotService,
        private messageService: MessageService,
    ) {
        this.title = 'Media Radar';
        this.confirmed = false;
    }
    onNotify(confirm): void {
        this.confirmed = confirm;
        if(this.confirmed) {
            this.preview.showPreview();
        }
    }
    ...
}

app.component.html

<div class='popup'>
    <h3>{{ title }}</h3>
    <screenshot [hidden]="confirmed" (showConfirm)='onNotify($event)'></screenshot>
    <confirm [hidden]="!confirmed" (hideConfirm)='onNotify($event)'></confirm>
    <preview [hidden]="!confirmed"></preview>
</div>

preview.component

import { ScreenshotService } from './screenshot.service';
@Component({
    selector: 'preview',
    template: `<canvas #preview></canvas>`
})
export class Preview {
    @ViewChild('preview') preview: ElementRef;
    private canvas: HTMLCanvasElement;
    constructor(
        private screenshotService: ScreenshotService,
        private renderer: Renderer2
    ) {}
    showPreview() {
        console.log(this.screenshotService) // shows a new instance with no data
    ...
    }
}

为了避免对代码太长,我将忽略服务和其他儿童组件,该组件首先称为,但可以在需要时发布。

update

ScreenShot.Service

import { Injectable } from '@angular/core';
@Injectable()
export class ScreenshotService {
    public imageURL: string = '';
    public title: string  = '';
    public height: number = 0;
    public width: number = 0;
    constructor() {
    }
    convertToBlob(): Promise<any> {
        console.log(this); // returns all the initial values above when called from the Preview component the second time despite being previously assigned values when a different method was called from a different service
    }
    ...
}

我的问题是在服务方法中。我将它们更改为箭头功能,并解决了所有问题。

最新更新