node.jsangulartypescriptsubscribeangular17

Is the method subscribe in angular 17 is not working


export class HomeComponent implements OnInit {

  data: any;

  constructor(private apiService: ApiService) { }

  ngOnInit(): void {
    // Substitua 'your-endpoint' pelo seu endpoint real
    this.apiService.getData('your-endpoint').subscribe(
      response => {
        this.data = response;
        console.log(this.data);
      },
      error => {
        console.error('Error fetching data', error);
      }
    );
  }
}

The subscribe method appears crossed out.


Solution

  • The comma separated method of passing next, error and complete callback is deprecated.

    .subscribe((data: any) => {}, (err: any) => {}, () => {}); // <- deprecated! 
    

    Try an object with next, error and complete properties, this syntax is not deprecated.

    this.apiService.getData('your-endpoint').subscribe({
          next: response => {
            this.data = response;
            console.log(this.data);
          },
          error: error => {
            console.error('Error fetching data', error);
          }
    });