来自不同打字稿文件的角度调用函数

时间:2018-06-26 03:18:53

标签: angular function service call

我从另一个打字稿文件调用函数/方法时遇到问题。我通读了许多文章,发现使用服务可以轻松完成,所以这里是我的代码,但无法正常工作。它不会引发任何错误,但也不会给出任何结果。

trigger.html

<button (click) = "openToast();" type="button" class="btn btn-primary btn-block">
  Open Toast
</button>

trigger.ts

import { Component, OnInit } from '@angular/core';
import { MessageService } from '../message.service';

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

  constructor(private _messageService: MessageService) { }

  ngOnInit() {
  }

  openToast(){
    this._messageService.callToastr();
  }

}

message.service

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessageService {
  invokeEvent = new Subject<any>();

  listen(): Observable<any> {
    return this.invokeEvent.asObservable();
  }

  callToastr(){
    this.invokeEvent.next('Y');
  }
  constructor() { }
}

home.ts

import { MessageService } from '../message.service';

const types = ['success', 'error', 'info', 'warning'];

@Component({
  templateUrl: './home.component.html',
  providers: [MessageService]
})
export class HomeComponent {

constructor(public toastr: ToastrService, private renderer: Renderer2, public _dataService: DataService,
              public _messageService: MessageService) {
    this.options = this.toastr.toastrConfig;
    this._messageService.listen()
    .subscribe( value => {
      if (value === 'Y') {
        this.openToast();
      }
    })
  }

 openToast() {
    const { message, title } = this.getMessage();
    // Clone current config so it doesn't change when ngModel updates
    const opt = cloneDeep(this.options);
    const inserted = this.toastr.show(
      message,
      title,
      opt,
      this.options.iconClasses[this.type],
    );
    if (inserted) {
      this.lastInserted.push(inserted.toastId);
    }
    return inserted;
  }
}

我已经尝试了很多方法,但是每次都失败了。任何人都可以帮助找到根本原因吗?预先感谢!

1 个答案:

答案 0 :(得分:1)

据我所知,您的方法链接正确。我想念的是ViewContainerRef。您必须至少设置一次,才能告诉Toastr出现的位置。请按照以下步骤在 home.ts 中扩展您的代码:

import { ViewContainerRef } from '@angular/core';

constructor(
    public toastr: ToastrService,
    public toastrMgr: ToastrManager, 
    private renderer: Renderer2,
    public _dataService: DataService,
    public _messageService: MessageService,
    private viewContainerRef: ViewContainerRef
) {
    this.toastrMgr.setRootViewContainerRef(viewContainerRef);

    // the rest of your code in constructor
}

请注意,如果将ViewContainerRef放在层次结构最高的组件中会容易得多。通常是这个app.component.ts。否则,您必须在应该显示烤面包机消息的每个单个组件中实现此VCR代码。

但首先,请尝试尝试此解决方案是否使home.ts中的烤面包机出现。