简体   繁体   中英

Why I am getting empty BehaviorSubject when accessing by url

I have such problem I am making demonstrative web page that rely on the blog system in angular8. The issue occurs there:

when I am using web link to route to the specified post unrolled then it works. But when I am using directly /post-details/3 it does not.

posts.component.ts

  postDetailsClick(i){
    this.getSharedBodies.subject.next(this.body);  //setting BehaviorSubject
    this.getSharedTitles.subject.next(this.titles);
    this.router.navigate(['/post-details', i]);      
  }

posts.component.html:

<mat-grid-list cols="3" rowHeight="150px">
    <mat-grid-tile
        *ngFor="let post of showPosts; let i = index" 
        [colspan]="post.cols"
        [rowspan]="post.rows"
        [style.background]="post.color">
      {{post.text}}
     <p><button  (click)="postDetailsClick(i)" >Try it</button></p>    
    <br>    
    </mat-grid-tile>
  </mat-grid-list>

post-details.component.html

export class PostDetailsComponent implements OnInit {
  indexOfPost;
  titles;
  // bodies = [];

  subscription: Subscription;
  renderPost:boolean=false;
  constructor(private activatedRoute:ActivatedRoute,private getSharedTitles:ShareInfoTitleService,private getSharedBodies: ShareInfoBodyService) {}


  ngOnInit() {
    this.indexOfPost=this.activatedRoute.snapshot.paramMap.get("id");
    console.log(this.getSharedTitles.subject.asObservable());

  }
}

line: console.log(this.getSharedTitles.subject.asObservable()); returns null observable when accessed directly by the url. But when clicked button it works properly.

export class ShareInfoTitleService {
  subject = new BehaviorSubject<any>(null);
  constructor() { }
  sendMessage(message: any[]) {
    this.subject.next({ titles: message });
  }
  clearMessages() {
    this.subject.next(null);
  }
  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

The problem is that you provide value to your BehaviorSubject only on click, so when you enter your component by link, last data in your BS is propably null. You must provide some data on start of component to get it.

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