如何使用服务注入组件。 Angular 4

时间:2018-06-13 18:22:50

标签: angular typescript angular-services angular-components

我是Angular 4的新手,我尝试创建一个显示加载框的组件,同时加载了一些内容...比如登录,加载图表等等。我不会&#39 ; t想要使用插件来做,因为我想学习如何做。 我使用CLI命令ng g component loading创建了组件,然后创建了一个调用方法来显示或隐藏组件的服务。

loading.component.ts

import { Component, OnInit } from '@angular/core';

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

  private loading = false;
  constructor() { }

  ngOnInit() {
  }

  public showLoad(){
    this.loading = true;
  }
  public hideLoad(){
    this.loading = false;
  }

}

loading.component.html

<div class ="box-loading" *ngIf="loading">
     <div id="loading"></div>
</div>

loading.service.ts

import { Injectable } from '@angular/core';
import { LoadingComponent } from '../../loading/loading.component';

@Injectable()
export class LoadingService {

  constructor(private loading: LoadingComponent) { }

  public showLoading(){
    this.loading.showLoad();
  }
  public hideLoading(){
    this.loading.hideLoad();
  }

}

当我调用showLoading()方法时,没有任何反应。所以我决定在我的登录页面上测试<app-loading></app-loading>,但是我收到了以下错误。

ERROR Error: Uncaught (in promise): Error: Template parse errors:
'app-loading' is not a known element:
1. If 'app-loading' is an Angular component, then verify that it is part of this module.
2. If 'app-loading' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
    <div class="login-box card">
        <div class="card-body">
            [ERROR ->]<app-loading *ngIf="loading"></app-loading>
            <form class="form-horizontal floating-labels" id="log"): ng:///LoginModule/LoginComponent.html@4:3

我将CUSTOM_ELEMENTS_SCHEMA添加到loading.module.ts和app.module.ts中的ngModule。

loading.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoadingComponent } from './loading.component';

@NgModule({
    declarations: [LoadingComponent],
    exports: [LoadingComponent],
    imports: [LoadingComponent],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA]
})
export class LoadingModule{}

如何将组件注入html页面?有最好的做法吗?我是在正确的方式吗?

3 个答案:

答案 0 :(得分:0)

您可以在服务中实现主题,并且组件按以下方式监听:

在服务中

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class LoadingService {

  showLoading = new EventEmitter<state>();

  public showLoading(){
    this.showLoading.emit(true);
  }
  public hideLoading(){
    this.showLoading.emit(false);
  }

}

在component.ts文件中,订阅服务中的eventEmitter。

import { Component, OnInit } from '@angular/core';

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

  private loading = false;
  constructor(private loadingService: LoadingService) { }

  ngOnInit() {
      this.loadingService.showLoading.subscribe(
         (state) => {
           this.loading = state;
         }
      );
  }
}

当然不要忘记将LoadingService添加到AppModule提供程序。

...
@NgModule({
    declarations: [LoadingComponent],
    imports: [ //You don't declare your components here, only the external modules you use in your project// ],
    providers: [LoadingService]
})
...

一般来说,服务用于服务组件,例如从服务器获取数据,或者组件之间的通信以及许多其他好处,你的思维方式对于Angular设计模式来说不是很好的做法,我想你需要在开始编码之前熟悉角度架构。

答案 1 :(得分:0)

您可以像这样加载LoadingComponent dynamicaly

1)在AppModule中,将LoadingComponent注册为entryComponents,如下所示:

&#13;
&#13;
 @NgModule({
    declarations: [LoadingComponent],
    entryComponents:  [LoadingComponent],
    providers: [LoadingService]
})
&#13;
&#13;
&#13;

2)在LoadingService中,实现方法show和hide,如下所示:

&#13;
&#13;
import {
    ApplicationRef, ChangeDetectorRef, Component,       ComponentFactoryResolver, ComponentRef, EmbeddedViewRef, Injector,
    } from '@angular/core';


@Injectable()
export class LoadingService {

  loadingCompRef: any;

  constructor(private loading: LoadingComponent,
               private componentFactoryResolver: ComponentFactoryResolver,
                private appRef: ApplicationRef,
                private injector: Injector,
) {}

  public showLoading(){
        // 1. Create a component reference from the component
         this.loadingCompRef = this.componentFactoryResolver
            .resolveComponentFactory(component)
            .create(this.injector);

        // bind data to component’s inputs
        this.loadingCompRef.instance.loading= true;
    
        // 2. Attach component to the appRef so that it's inside the ng component tree
        this.appRef.attachView(this.loadingCompRef.hostView);

        // 3. Get DOM element from component
        const domElem = (this.loadingCompRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

        // 4. Append Loding DOM element to the body
        // `my-loader` is the `HTML id` attribut where you want to append you loader 
        document.getElementById('my-loader').appendChild(domElem);

  }
  
  public hideLoading(){
      this.loadingCompRef.instance.loading= false;
      this.appRef.detachView(this.loadingCompRef.hostView);
      this.loadingCompRef.destroy();
  }

}
&#13;
&#13;
&#13;

有关Angular中Dynamic loading of components的更多详情,请点击此处: https://angular.io/guide/dynamic-component-loader

答案 2 :(得分:0)

更简单的方法是实现这样的Loading组件:

&#13;
&#13;
import {Component, Input, OnInit} from '@angular/core';

@Component({
    ...
})
export class LoadingComponentimplements OnInit {

    @Input() isLoading: boolean = false;

    constructor() {
    }

    ngOnInit() {
    }

}
&#13;
&#13;
&#13;

使用LoadingCompoenent

mat-spinnerAngular Material的HTML中

&#13;
&#13;
<div class="loading-shade" *ngIf="isLoading">
    <mat-spinner></mat-spinner>
</div>
&#13;
&#13;
&#13;

CSS

中的

&#13;
&#13;
.loading-shade {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.15);
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}
&#13;
&#13;
&#13;

然后在LoadingCompoenent

中注册AppModule

&#13;
&#13;
@NgModule({
    declarations: [LoadingComponent]
})
&#13;
&#13;
&#13;

最后在你的应用程序中的任何地方调用它,只需给出@Input()任何组件中定义的loading变量,如下所示:

在该组件中获取内容的模板顶部,添加LoadingCompoenent的选择器

&#13;
&#13;
// TYPESCRIPT

loading: boolean;

doStuff(){
  this.loading = true;
  ...
  this.loading = false;
}

// HTML

<app-loading [isLoading]="loading"></app-loading>

<h1>TITLE</h1>
&#13;
&#13;
&#13;