Laharee
Laharee

Reputation: 21

When accessing another component's function in Angular, this keyword is not working

export class ComponeComponent implements OnInit {

  constructor(private cService: CService, private toastr: ToastrService) { }

  //class variable so that I can assign perticular client object
  clientObj: any;

  //to get all the client
  clients: any[] = [];

  /**
   * getting all the clients
   */
  ngOnInit() {
    this.cService.getClient().subscribe(
      (page: any) => {
        this.clients = page.payload;
      }
    );
    this.toastr.warning("Sorry, problem in loading records in client");
  }

  ....

  /**
   * Deleting particular Client
   */
  deleteClient() {
    this.cService.deleteClient(this.clientObj.id).subscribe(
      response => {
        console.log('Client record Deleted!', response);
        console.log(this.clientObj.id);
        this.toastr.error("Client record Deleted");
        console.log(this.clientObj.id);
        this.ngOnInit();
      }
    );
  }
}

Now every console.log is working fine within deleteClient but not this.toastr.error("Client record Deleted"); or this.ngOnInit(); When I am clicking any other button in sidebar component then the toast is working.

I am calling this deleteClint() from another component which is in different module also.

This is in my app module

....
import { ToastrModule } from 'ngx-toastr';

@NgModule({
  declarations: [
    ....
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    FormsModule,
    ToastrModule.forRoot({
      closeButton: true,
      enableHtml: true,
      timeOut: 5000,
      positionClass: 'toast-top-right',
    }),
    BrowserAnimationsModule,
    HttpClientModule
  ],

I have tried rearranging the position where I am calling toast, as I thought it's not working after console.log. But it's not that. I have tried different toast positions, but that's not that problem. After console.log in different line, It's clear that, it's skipping lines with this keyword. AGAIN, it's not like toast is not working. Suppose this is client component opening with client button in sidebar. When I am clicking home or staff (suppose) in sidebar with sec, I can see the toast there. Otherwise never. I have also tried assigning this keyword in a const var.

Upvotes: 2

Views: 96

Answers (0)

Related Questions