AlexGH
AlexGH

Reputation: 2805

using BehaviorSubject and not getting the value expected

I'm using a service globally and BehaviorSubject to share the BehaviorSubject property value in two components for now... This is my service:

@Injectable()
export class JobsService {
private partitionKeySource = new BehaviorSubject("not retrieved yet");

    partitionKey$ = this.partitionKeySource.asObservable();

    constructor(private _http: Http) {

    }

  getJobs(): Observable<Job[]> {
    return this._http.get(this._jobsUrl).map((response: Response) => <Job>response.json())
   .catch(this.handleError);
    }

    setPartitionKey(partitionKey: string) {
        this.partitionKeySource.next(partitionKey);


      }
}

This is the JobsComponent, I'm calling the setPartitionKey() method of my service and passing a value to it as a parameter from this component:

export class JobsComponent implements OnInit {
 ngOnInit(): void {
this._jobsService.getJobs().subscribe((data: Job[]) => {//...some code})};
constructor(private _jobsService: JobsService, private router: Router) {}
select(partitionKey: string) {
        this._jobsService.setPartitionKey(partitionKey);
        this._jobsService.partitionKey$.subscribe(response => {
            console.log('from jobs component the partitionKey value is: ' + response);
            console.log('after getting the response jobsComponent');
            this.router.navigateByUrl('/app/job_details');
        }, error => console.log('there was an error: ' + error));
    }

This is the JobsComponent html:

<div class="jobContainer" *ngIf="isThereAnyJob === true">
    <div *ngFor="let job of jobs">
        <a (click)="select(job.PartitionKey)">{{job.Title}}</a>
    </div>
</div>

And this is the JobDetails component:

export class JobDetailsComponent{
constructor( private _jobsService: JobsService) {
        console.log('constructor called from JobDetails');
        this._jobsService.partitionKey$.subscribe(response => {
                console.log('from job details Component the partitionKey value is: ' + response);
            },
            error => console.log('there was an error from job details component: ' + error));
    }

I'm putting the JobsService globaly in the @NgModule:

@NgModule({
    imports://....
    declarations://....
    bootstrap: [AppComponent],
    providers: [Globals, JobsService, MissionService]
})
export class AppModule {}

So when I set the partitionKeySource value of my service I want to navigate to the JobDetails component to display the details of that job using the partitionKey value, I'm using global service and BehaviorSubject because I don't want to display the partitionKey value in the url...

When it navigates to JobDetails the value of partitionKey is the default one set on the JobsService instead of the Job partitionKey in particular... I'm using console.log() to print the order and the partitionKey value of both components, which I want to be the same...

This is what is being printed:

from jobs component the partitionKey value is: 01f1f352-51e0-474e-962b-a75a56925342d 
after getting the response jobsComponent
constructor called from JobDetails
from job details Component the partitionKey value is: not retrieved yet

I want the partitionKey value to be the same in both components(01f1f352-51e0-474e-962b-a75a56925342d)... Why JobDetails is getting the default value if this is changed before using JobsComponent?

Upvotes: 0

Views: 596

Answers (1)

LLai
LLai

Reputation: 13396

From the order of the provided console log outputs, it looks like there are multiple instances of your service. Remove all instances of the JobsService from your Component providers and only keep it in the providers array of your AppModule

@Component({
    providers: [ JobsService ] // remove this
})

This will make JobsService a singleton service that can be shared across all components in the application.

Upvotes: 1

Related Questions