我的代码有问题吗?我需要通过 Angular 中使用的服务方法将标头组件中选择的"字符串"传递给应用程序组件



我正在创建一个购物清单项目,我试图通过服务将选定的数据从我的header.component.html传递到app.component.ts,然后尝试在app.component.ts中仅控制台.log。但是我看到控制台.log app.component.ts的语句中没有打印任何内容,也没有收到任何错误。

这也是它的要点链接,代码也在下面。任何帮助将不胜感激。

https://gist.github.com/ratnabh/87847c8396a32436b8a751eb5bb08ae8

我在这里使用了服务。

Header.component.html

<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
  <a href="#" class="navbar-brand">Recipe Book</a>
</div>
<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li><a href="#" (click)="clicked('recipe')">Recipes</a></li>
    <li><a href="#" (click)="clicked('shoping')">Shopping list</a></li>
  </ul>
  <ul class="nav navbar-nav navbar-right">
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" role="button">Manage<span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Save Data</a></li>
        <li><a href="#">Fetch Data</a></li>
      </ul>
    </li>
  </ul>
</div>

Header.component.ts

import { Component, OnInit } from '@angular/core';
import { Headerrecipe } from './header.service';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
  providers:[Headerrecipe]
})
export class HeaderComponent implements OnInit {
  constructor(private heservice:Headerrecipe) { }
  ngOnInit() {
  }
  clicked(e:string){
  this.heservice.stringselected.emit(e)
  }
}

Header.service.ts

import { EventEmitter } from '@angular/core';
export class Headerrecipe{
  stringselected=new EventEmitter<string>()
}

App.component.ts

import { Component, OnInit } from '@angular/core';
import { Headerrecipe } from './header/header.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[Headerrecipe]
})
export class AppComponent implements OnInit{
  selected='recipe'
  ngOnInit(){
   this.heservice.stringselected.subscribe((item)=>{
   this.selected=item
   console.log(this.selected)
   })
  }
  constructor(private heservice:Headerrecipe){}
}

如果您使用的是 Angular v6 或更高版本,则可以使用以下语法向根 Angular 注入器注册服务:

import { EventEmitter } from '@angular/core';
@Injectable({providedIn: 'root'})
export class Headerrecipe{
  stringselected = new EventEmitter<string>()
}

然后,该服务不需要包含在任何模块或组件的providers数组中。

以这种方式注册服务会将其注册到提供共享实例的根 Angular 注入器。因此,您可以使用此技术在应用程序的任何组件之间共享数据。

在您的标头服务中,可以考虑使用 rxjs 中的Subject然后创建一个方法,用于更新服务中该主题的值 ex

// header.service.ts
selectedRecipe: Subject<any> = new Subject();

chooseRecipe(recipe: string) {
    this.selectedRecipe.next(recipe);
}
// header.component.ts
yourClickMethod(recipe: string) {
   this.heservice.chooseRecipe(recipe);
}
your app component logic would stay the same, the subscribe will work the same way.

最新更新