How can I get my data on the subscriber in my component.ts file

Viewed 25

The component .ts

post!: Post;
  subscriptionPost: any;
  postId!: number;
  constructor(
    private activatedRoute: ActivatedRoute,
    private postService: PostsService,
  ) {}

  ngOnInit(): void {
    this.activatedRoute.params.subscribe(
      (params) => this.postId = params['id']
    )
    this.subscriptionPost = this.postService.getPostById(this.postId).subscribe(
       data => this.post = data
    )
    console.log(this.post)          // output: undefined

    console.log('the post id: ' + this.postId);    //output: 12 : this is right
  }

My problem is that if I console.log(this.post) : it shows me undefined but when I {{ post | json }} it in the template.html -> it shows my needed data. But actually I need It also in my component.ts because I want to share it to other component

Because if I stay like that, when I Input it(post) on other component, It has undefined value

Do someone knows how can I get the data to my post ?

0 Answers
Related