简体   繁体   中英

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

I have Component A, Component B, and a service. I declared Subject in the service and subscribed the Subject in component B., And I'm sending some data from Component A to the Subject before navigating to component B. It is navigating to component B, but the Subscribe method is not triggering.

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

}

Sending the message to observable 将消息发送给可观察者

@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]);

  }
}

Here I subscribed the Observable. 我在这里订阅了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}`); }
);

}

}

It's navigating from Component A to Component B but the subscribe method is not triggering in Component B. Please suggest.

Use BehaviorSubject instead, so that you always get the current value (latest) that was emitted before the new subscription.

If you are using Subject , then you only get values that are emitted after subscription.

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

Diff between Subject and BehaviorSubject

Thanks for the Idea @Amit. I used ReplaySubject(1) and it is working perfectly.

recipeSelected = new ReplaySubject<any>(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM