Home > other >  how to pass data between 2 unrelated components by using subjects in angular?
how to pass data between 2 unrelated components by using subjects in angular?

Time:10-25

Here I'm trying to pass an id from component1 to my service and I'm using the subject to emit that id inside the service. I'm trying to subscribe to that subject from component2 to get the id. But I'm not able to get the id.

component1


    export class ContestUploadButtonComponent implements OnInit {
            contestId:any
            ngOnInit(): void {
            this.contestId = this.contest
            this.frontEnd.contestData(this.contestId)
              }
       

      }

service


    @Injectable({
      providedIn: 'root'
    })
    export class FrontendService {
    
      constructor() { }
    
      contest = new Subject<string>()
    
      contestData(data:string){
         this.contest.next(data)
      }
    
      dialogData():Observable<string>{
        return this.contest.asObservable()
      }
    }

component 2


    export class ContestUploadDialogComponent implements OnInit {
    
      file:File|any
      filePath!:string;
      contestId:string=""
    
      constructor(private backEnd : BackendService,private frontEnd:FrontendService) { }
    
      ngOnInit(): void {
        this.frontEnd.dialogData().subscribe((contestId)=>{
          console.log(contestId);
          this.contestId = contestId
    
        })
      }

CodePudding user response:

Please try to change your Subject to ReplaySubject(1) -> then your new subscription should get last emitted data from Observable

1 in example meat count of last emitted data to Observable

CodePudding user response:

Small addition to @gzn, it may happen due to order in which ngOnInit methods are called, so you should save last emitted value and give it to a new subscribers. In this case you can try using BehaviouralSubject or ReplaySubject(1) as was already told

  • Related