Creating and using component at angular 2

Asked

Viewed 80 times

0

I created this component to show success message or not.

import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.css']
})
export class SnackBarComponent {

  snackBar: MatSnackBar

  constructor(

  ) {}

  openSnackBar(message: string, isOnline : boolean) {
    this.snackBar.open(message, undefined, 
      { duration: 3000, 
        panelClass: isOnline ? ["online", "onlineAction"] : "offline" }
      );
  }
}

To call I’m doing so:

onSubmit(form){
    const snackBarComponent = SnackBarComponent;
    snackBarComponent.prototype.openSnackBar(dados.mensagem, true);
}

Only it shows this error in the browser console:

ERROR TypeError: Cannot read property 'open' of undefined
        at Object.SnackBarComponent.openSnackBar (snack-bar.component.ts:18)
        at MunicipioFormComponent.onSubmit (municipio-form.component.ts:115)
        at Object.eval [as handleEvent] (MunicipioFormComponent.html:1)
        at handleEvent (core.js:13547)
        at callWithDebugContext (core.js:15056)
        at Object.debugHandleEvent [as handleEvent] (core.js:14643)
        at dispatchEvent (core.js:9962)
        at eval (core.js:12301)
        at SafeSubscriber.schedulerFn [as _next] (core.js:4343)
        at SafeSubscriber.__tryOrUnsub (Subscriber.js:243)
    View_MunicipioFormComponent_0 @ MunicipioFormComponent.html:1
    proxyClass @ compiler.js:14653
    DebugContext_.logError @ core.js:14996
    ErrorHandler.handleError @ core.js:1509
    dispatchEvent @ core.js:9966
    (anonymous) @ core.js:12301
    schedulerFn @ core.js:4343
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:243
    SafeSubscriber.next @ Subscriber.js:190
    Subscriber._next @ Subscriber.js:131
    Subscriber.next @ Subscriber.js:95
    Subject.next @ Subject.js:56
    EventEmitter.emit @ core.js:4311
    NgForm.onSubmit @ forms.js:5762
    (anonymous) @ MunicipioFormComponent.html:1
    handleEvent @ core.js:13547
    callWithDebugContext @ core.js:15056
    debugHandleEvent @ core.js:14643
    dispatchEvent @ core.js:9962
    (anonymous) @ core.js:10587
    (anonymous) @ platform-browser.js:2628
    ZoneDelegate.invokeTask @ zone.js:421
    onInvokeTask @ core.js:4740
    ZoneDelegate.invokeTask @ zone.js:420
    Zone.runTask @ zone.js:188
    ZoneTask.invokeTask @ zone.js:496
    invokeTask @ zone.js:1517
    globalZoneAwareCallback @ zone.js:1543
    MunicipioFormComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}

What can it be ?

  • To call would not be so: snackBarComponent.openSnackBar(dados.mensagem, true); ?

1 answer

1

You’re not initiating the snackbar, you have to put it in the builder by angular inject it.

import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.css']
})
export class SnackBarComponent {     

  constructor(
      private snackBar: MatSnackBar,
      private messageService: MessageService
  ) {
  this.message.getMessages().subscribe(message=>this.openSnackBar(message.message, message.isOnline ))
}

  openSnackBar(message: string, isOnline : boolean) {
    this.snackBar.open(message, undefined, 
      { duration: 3000, 
        panelClass: isOnline ? ["online", "onlineAction"] : "offline" }
      );
  }
}

message.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MessageService{
    private messageSubject= new Subject<any>();

    constructor() {}

    addMessage(message) {
        this.messageSubject.next(message);
    }

    getMessages(): Observable<any> {
        return this.messageSubject.asObservable();
    }
}
  • Yes, I did what you said. There was no error because, I understand that I did not call this component. What do I call ? If I do this, it gives the same error. const snackBarComponent = Snackbarcomponent; snackBarComponent.prototype.openSnackBar(data.message, true); ?

  • Do you want to call from the same component? If yes you can call it this: this.openSnackBar(data.message, true);

  • No. Example. There are the components: Neighborhood, Bairrobusca, State, Statessusca, among others, more than 50. The idea is to create this component and call in the forms by passing the parameters when necessary. Got it ?

  • in this case you need to create a service that you inject into other Components with a Subject behavior that you receive the parameters you show when necessary. I’ll edit my answer to give you an idea.

  • Ai to call in the Neighborhood would be like this: In the constructor, I put like this: private messageService : Messageservice; ai in execution like this: messageService.addMessage("my message"); Correct ?

  • type this or so you can make an object with the message and the boolean or an array goes from vc.

  • It would be right to create an export interface Message {message:string, isOnline:Boolean}

  • ai coloca la addMessage(message:Message)

  • Blz. I will try to solve here and put the result. Anyway thank you.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.