0

服务.ts:

  private showBoxAction = new Subject<any>();
  showBox = this.showBoxAction.asObservable();
  openBox() {
    console.log("in Box");

    this.showBoxAction.next(true);
  }

组件1.html

 <ng-template #noMsgs>
                  <div id="top" class="container">
                    <div class="row">
                      <div class="col-xs-12 explorer-results">
                        <div class="no-results-found">
                          <div class="joinUs">
                                <span>
                                  <p >Join us.</p>
                                  <a href="javascript:" (click)="showBox()" class="mat-button default">Start Now</a>
                                </span>
                            </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </ng-template>

组件1.ts

      providers: [, DatePipe, FragmentParamsPipe],
import { environment } from "./../../../../environments/environment";
import { Http, ConnectionBackend } from "@angular/http";
import {
  Component,
  OnInit,
  OnDestroy,
  AfterViewInit,
  HostListener,
  Inject,
  NgZone,
  ViewChild,
  ElementRef,
  Output
} from "@angular/core";
import { DOCUMENT, Title } from "@angular/platform-browser";


import { Subscription } from "rxjs/Subscription";
import {
  CONSTANT,
  FEATURE,
  flattenJSON,
  unflattenJSON
} from "../../../Constants";
import { Observable } from "rxjs/Observable";
import { MatDialog, MatDialogRef } from "@angular/material";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Subject } from "rxjs/Subject";
import { Router, NavigationEnd, ActivatedRoute } from "@angular/router";
import { TabsetComponent } from "ngx-bootstrap";
import { Service } from "/src/app/services/service";
import { FragmentParamsPipe } from "../../../pipes/url/fragment-params.pipe";

declare let jQuery: any;
@Component({
  selector: "component1",
  templateUrl: "./component1.component.html",
  styleUrls: ["./component1.component.css"],
  providers: [QuestionControlService, DatePipe, FragmentParamsPipe],
  entryComponents: [DialogBoxComponent, MasterListComponent]
})
export class UserProfileComponent implements OnInit, OnDestroy, AfterViewInit {

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private _service: Service,

  ) {


  }

  ngOnInit() {

  }


  /**
   * Display messageBox component.
   */
  showBox() {
      this._service.openComposeBox();
  }

  ngAfterViewInit() {

  }



  ngOnDestroy(): void {
  }




  }

组件2.ts

 private subscriptions = new Subscription();

  constructor(private _service:Service)
{

    this.subscriptions.add(
      this._service.showBox.subscribe(event => {
        if (event) {

        console.log("display box");
        }
      })
    );
}

当我单击 show-box 触发 showBox() 函数时,我在控制台“in Box”中得到输出,但没有得到控制台“显示框”,即未订阅 observable。当我的下一个触发器调用 openBox() 然后 observable 订阅成功时,可能是什么原因。我的实施有什么问题?

更新

问题只是当我通过 component1.ts 调用它时,这是我第一次在应用程序中使用它。我已经尝试订阅而不将其添加到订阅中。

组件2.ts

 ngOnInit() {
    this._service.showBox.takeUntil(this.destroy$).subscribe(event => {

      if (event) {
        this.displayCompose = true;
        console.log("display box");
      }
    })

  }



 ngOnDestroy(): void {

    this.destroy$.next(true);
    // Now let's also unsubscribe from the subject itself:
    this.destroy$.unsubscribe();

    this.subscriptions.unsubscribe();
  }
}

更新

我在帖子中提到的应用程序和组件的结构: my-angular-app\src\app\components\component1\componen1.ts

my-angular-app\node_modules\angular-app2\components\component2-parent\component2-parent.ts

my-angular-app\node_modules\angular-app2\components\component2\component2.ts Component1.component.html:

     <ng-template #noMsgs>
                      <div id="top" class="container">
                        <div class="row">
                          <div class="col-xs-12 explorer-results">
                            <div class="no-results-found">
                              <div class="joinUs">
                                    <span>
                                      <p >Join us.</p>
                                      <a href="javascript:" (click)="showBox()" class="mat-button default">Start Now</a>
                                    </span>
                                </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </ng-template>

<component2-parent *ngIf="display"></component2-parent>

component1.ts

export class Component1 
showBox()
{
this.display = true;
_service.openBox()
}

component2-parent 包含 component2。

4

2 回答 2

2

使用BahaviourSubject, 这样你就不会错过初始值,

private showBoxAction = new BehaviorSubject <any>();

并在里面添加您的订阅ngOnInit()(良好做法),而不是constructor.

ngOnInit() {
  this._service.showBox.subscribe(event => {
    if (event) {
      this.displayCompose = true;

    console.log("display box");
    }
  })
于 2018-07-14T16:17:32.887 回答
0

好吧,我们换一种方式试试。

而不是你的 service.ts 中的这行代码

showBox = this.showBoxAction.asObservable();

把这个方法

getShowBoxAction(): Observable<any> {
   return this.showBoxAction.asObservable();
}

并在您的 component2.ts 中以这种方式订阅

// of course you can add this to your subscriptions-object as well.
this._service.getShowBoxAction().subscribe( event => {

    // the rest of your code

});

编辑:2018 年 7 月 15 日下午 1.29

您没有调用正确的服务。这是您当前在组件 1 中调用的内容:

// **
   * Display messageBox component.
   */
    showBox() {
        this._mailingService.openComposeBox();
    }

但是你必须调用你的 service.ts!

showBox() {
    this._service.openBox();
}

请更换任何代码试一试。

于 2018-07-14T21:09:07.093 回答