簡體   English   中英

在Angular 6中從一個組件導航到另一個組件時,主題無法正常工作

[英]Subject is not working when route navigating from one component to another component in Angular 6

我有組件A,組件B和服務。 我在服務中聲明了Subject,並在組件B中訂閱了Subject。在導航到組件B之前,我正在從組件A向主題發送一些數據。它正在導航到組件B,但沒有觸發Subscribe方法。

服務:

@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中觸發subscription方法。請提出建議。

請改用BehaviorSubject ,以便始終獲得在新訂閱之前發出的當前值(最新)。

如果您使用的是Subject ,那么您只能獲取訂閱后發出的值。

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

主體與行為主體之間的差異

感謝您的想法@Amit。 我使用了ReplaySubject(1) ,它運行良好。

recipeSelected = new ReplaySubject<any>(1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM