简体   繁体   中英

Typescript: use private object in static function

How can i use Angular Material with Typescript in a pretty-code way?

For example, i do not want to write in every place where i use SnackBar this:

constructor(public snackBar: MdSnackBar) {}


***
this.snackBar.open('text', {
  duration: 500
}); // and i need to add this yet 10 times: no to good
***

i want to create a separate class, and call only it (static function), like:

constructor(private snackBar: MdSnackBar) {
}

public static showSnackBar(text: string, config: string): void {
  this.snackBar.open(text, config);
}

but so i got error:

Property 'snackBar' does not exist on type 'typeof SnackBar'.

when i transform my code:

  static snackBar: MdSnackBar;

  constructor() {
  }

  public static showSnackBar(text: string, config: string): void {
    SnackBar.snackBar.open(text);
  }

and call it from another classed, i got:

EXCEPTION: Cannot read property 'open' of undefined
ErrorHandler.handleError @ error_handler.js:47
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
ZoneDelegate.handleError @ zone.js:236
Zone.runTask @ zone.js:157
ZoneTask.invoke @ zone.js:335
error_handler.js:52 ORIGINAL STACKTRACE:
ErrorHandler.handleError @ error_handler.js:52
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
ZoneDelegate.handleError @ zone.js:236
Zone.runTask @ zone.js:157
ZoneTask.invoke @ zone.js:335
error_handler.js:53 TypeError: Cannot read property 'open' of undefined
    at Function.SnackBar.showSnackBar (snack-bar.ts:13)
    at SafeSubscriber._next (edit.component.ts:78)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:223)
    at SafeSubscriber.next (Subscriber.js:172)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at CatchSubscriber.Subscriber._next (Subscriber.js:125)
    at CatchSubscriber.Subscriber.next (Subscriber.js:89)
    at MapSubscriber._next (map.js:83)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
ErrorHandler.handleError @ error_handler.js:53
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
ZoneDelegate.handleError @ zone.js:236
Zone.runTask @ zone.js:157
ZoneTask.invoke @ zone.js:335
Subscriber.js:227 Uncaught TypeError: Cannot read property 'open' of undefined
    at Function.SnackBar.showSnackBar (snack-bar.ts:13)
    at SafeSubscriber._next (edit.component.ts:78)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:223)
    at SafeSubscriber.next (Subscriber.js:172)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at CatchSubscriber.Subscriber._next (Subscriber.js:125)
    at CatchSubscriber.Subscriber.next (Subscriber.js:89)
    at MapSubscriber._next (map.js:83)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
SnackBar.showSnackBar @ snack-bar.ts:13
(anonymous) @ edit.component.ts:78
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
MapSubscriber._next @ map.js:83
Subscriber.next @ Subscriber.js:89
onLoad @ xhr_backend.js:72
ZoneDelegate.invokeTask @ zone.js:265
onInvokeTask @ ng_zone.js:227
ZoneDelegate.invokeTask @ zone.js:264
Zone.runTask @ zone.js:154
ZoneTask.invoke @ zone.js:335

what i do wrong, what i misunderstood?

如果它是静态函数,则只能使用'this'的静态成员

You can create static methods in a class and then import them by the class name.

Example:

export class AStaticServiceClass {

  static doStuff(){
    return "I'm Static";
  }
}

and use it wherever you want as:

this.name = AStaticServiceClass.doStuff();

by importing the class.

Full plunker example: http://plnkr.co/edit/NWRSuaUpzkPEP3gL1DKK?p=preview

Here is the solution I used with same situation like in the question content.

Step 1: Crate a class with static function for show the message using snackbar

export class AlertMessageUtils {

  private static snackBar: MatSnackBar;         

  public static setSnackBar(snackBar: MatSnackBar){

    this.snackBar = snackBar;
  }

  public static showAlert(message: string, duration: number, positionV: any, positionH: any){
 
    this.snackBar.open(message, 'Close', {
      duration: duration * 1000,
      verticalPosition: positionV,
      horizontalPosition: positionH
    });
  }

}

Step 2: update the app component - set the MatSnackBar into the AlertMessageUtils class.

export class AppComponent implements AfterViewInit {

  constructor(private snackBar: MatSnackBar ){ }  

  ngAfterViewInit() {
   
    AlertMessageUtils.setSnackBar(this.snackBar);
  }

}

Step 3: Now we can use the AlertmessageUtils all over the application by Just calling its static function like follows

AlertMessageUtils.showAlert('This is a test message...', 5, 'top', 'center');

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