angular2中的发射器服务使用订阅在ts文件中重新获取数据但不在html中显示数据

时间:2016-11-04 10:20:43

标签: angular typescript eventemitter

我是角度2的新手。在我的项目中,我有2个组件,一个是带有文本字段的searchcomponent,另一个组件是displayComponent。在输入某个值后的输入字段中按enter键,使其必须使用eventemitter服务(不是@input和@output)显示在displaycomponent中。 查看图片image1 image2

代码是

emitter.service.ts

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


@Injectable()
export class EmitterService {
  private static _emitters: { [channel: string]: EventEmitter<any> } = {};
  static get(channel: string): EventEmitter<any> {
    if (!this._emitters[channel])
      this._emitters[channel] = new EventEmitter();
    return this._emitters[channel];
  }
}

searchComponent.html

<div>Search and clear</div>
<input type="text" value="{{inputTerm}}" (keyup.enter)="alertInput(input1.value)" #input1/>

searchComponent.ts

import {Component} from '@angular/core';
import {EmitterService} from '../emitter.service';


@Component({
  selector: 'search',
  templateUrl: './Task1-search.html'
})
export class SearchComponent {

    inputTerm:string;
    menubarEmitter = EmitterService.get("displayText");

    alertInput(val1){
        this.inputTerm=val1
        alert("user clicked enter to see input value is "+this.inputTerm);
        this.menubarEmitter.emit({"InputText":this.inputTerm});
    }    
}

displaycomponent.html

<div>The name entered in input field is {{displayValue}}</div>

dispalycomponent.ts

import {Component} from '@angular/core';
import {EmitterService} from '../emitter.service';

@Component({
  selector: 'display',
  templateUrl: './Display-input.html',

})
export class DisplayComponent {

  displayValue:string;
  menubarEmitter = EmitterService.get("displayText");

  constructor(){
    this.menubarEmitter.map((res:any)=>res).subscribe(val => {
      if(val.InputText==undefined || val.InputText==""){
        // this.displayValue=val.InputText;
        console.log("wrong");
      }
      else{
        console.log("right");
        this.displayValue=val.InputText;

      }
      console.log("display "+this.displayValue);
    });
  }
}

的package.json

{
  "name": "angular2-seed",
  "version": "1.0.0",
  "description": "A simple starter Angular2 project",
  "scripts": {
    "build": "webpack --inline --colors --progress --display-error-details --display-cached",
    "watch": "npm run build -- --watch",
    "server": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src",
    "start": "npm run server"
  },
  "contributors": [
    "Rob Wormald <robwormald@gmail.com>",
    "PatrickJS <github@gdi2290.com>"
  ],
  "license": "MIT",
  "devDependencies": {
    "@types/core-js": "^0.9.32",
    "@types/node": "^6.0.38",
    "angular2-template-loader": "^0.4.0",
    "awesome-typescript-loader": "^1.1.1",
    "css-loader": "^0.23.1",
    "raw-loader": "^0.5.1",
    "to-string-loader": "^1.1.4",
    "typescript": "^2.0.2",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0",
    "webpack-merge": "^0.8.4"
  },
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "core-js": "^2.4.1",
    "ie-shim": "^0.1.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "~0.6.23",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.7"
  },
  "keywords": [
    "Angular2",
    "angular2-seed",
    "official angular 2 seed",
    "official angular2 seed"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/angular/angular2-seed.git"
  },
  "bugs": {
    "url": "https://github.com/angular/angular2-seed/issues"
  },
  "homepage": "https://github.com/angular/angular2-seed#readme"
}

app.module.ts

import {NgModule} from '@angular/core'
import {RouterModule} from "@angular/router";
import {rootRouterConfig} from "./app.routes";
import {AppComponent} from "./app.component";
import {GithubService} from "./github/shared/github.service";
import {FormsModule} from "@angular/forms";
import {BrowserModule} from "@angular/platform-browser";
import {HttpModule} from "@angular/http";
import {AboutComponent} from './about/about.component';
import {HomeComponent} from './home/home.component';
import {RepoBrowserComponent} from './github/repo-browser/repo-browser.component';
import {RepoListComponent} from './github/repo-list/repo-list.component';
import {RepoDetailComponent} from './github/repo-detail/repo-detail.component';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {EventEmitter, Injectable} from '@angular/core';

import {SearchComponent} from "./Task1-search/Task1-search";
import {DisplayComponent} from "./Display-input/Display-input";
import {EmitterService} from "./emitter.service";

@NgModule({
  declarations: [AppComponent, AboutComponent, RepoBrowserComponent, RepoListComponent, RepoDetailComponent, HomeComponent, SearchComponent, DisplayComponent],
  imports     : [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(rootRouterConfig)],
  providers   : [GithubService, {provide: LocationStrategy, useClass: HashLocationStrategy}, EmitterService],
  bootstrap   : [AppComponent]
})
export class AppModule {

}

app.component.ts

从@ angular / core&#39;;

导入{Component}
@Component({
  selector   : 'app',
  templateUrl: './app.component.html',
})
export class AppComponent {
}

app.component.html

<h3>
  Angular 2 Seed
</h3>
<nav>
    <!--<a [routerLink]="['/']">
    Home
  </a>
  |
    <a [routerLink]="['/about']">
    About
  </a>-->
  |
  <a [routerLink]="['/search']">
    Search
  </a>
  |
  <a [routerLink]="['/display']">
    Display
  </a>
  |
    <!--<a [routerLink]="['/github', 'angular']">
    Github Repos
  </a>-->
</nav>

<main>
    <router-outlet></router-outlet>
</main>


<footer>
  © 2016
</footer>

任何人都可以帮助解决这些问题。提前完成。

1 个答案:

答案 0 :(得分:1)

尝试ChangeDetectorRef

constructor(private changeDetectorRef: ChangeDetectorRef) {
  this.menubarEmitter.map((res:any)=>res).subscribe(val => {
    if(val.InputText==undefined || val.InputText=="") {
      console.log("wrong");
    } else {
      console.log("right");
      this.displayValue=val.InputText;
      this.changeDetectorRef.detectChanges();
    }
    console.log("display "+this.displayValue);
  });
}