在Angular 6中从一个组件导航到另一个组件时,主题无法正常工作

时间:2019-02-11 15:25:50

标签: angular subject

我有组件A,组件B和服务。我在服务中声明了Subject,并在组件B中订阅了Subject。在导航到组件B之前,我正在从组件A向主题发送一些数据。它正在导航到组件B,但是Subscribe方法未触发。 / p>

服务:

@Injectable({
  providedIn: 'root'
})
export class ServiceTestService {
storage: Recipe;
recipeSelected = new Subject<any>();
constructor() { }

}

组件A 将消息发送到可观察的

@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html'
 })

export class RecipeItemComponent implements OnInit {

@Input() recipe: Recipe;

  constructor(
     private recipeService: ServiceTestService,
     private rt: Router) { }

  ngOnInit() {
  }

  onRecipeSelected(name: number) {

this.recipeService.recipeSelected.next(this.recipe);
this.rt.navigate(['/recipe', this.ind]);

  }
}

组件B:在这里,我订阅了Observable。

@Component({
  selector: 'app-recipe-detail',
  templateUrl: './recipe-detail.component.html',
  styleUrls: ['./recipe-detail.component.css']
  })

export class RecipeDetailComponent implements OnInit, OnDestroy {
  recipe: Recipe;

  constructor(private recipeService: ServiceTestService) { }

ngOnInit() {

this.recipeService.recipeSelected.subscribe(

  (res: any) => {
    console.log(`Recipe Component ${res}`); }
);

}

}

它正在从组件A导航到组件B,但是订阅方法未在组件B中触发。请提出建议。

2 个答案:

答案 0 :(得分:3)

请改用BehaviorSubject,以便始终获得在新订阅之前发出的当前值(最新)。

如果您使用的是Subject,则只能获取订阅后发出的值。

export class ServiceTestService {
   storage: Recipe;
   recipeSelected = new BehaviorSubject<any>();
   constructor() { }
}

Diff between Subject and BehaviorSubject

答案 1 :(得分:1)

感谢Idea @Amit。我使用了ReplaySubject(1),它运行良好。

recipeSelected = new ReplaySubject<any>(1);