Open web-dave opened 7 years ago
{ "routing": {...}, "external": {...}, "dynamic": {...}, "push": { "showNotifications": true, "backgroundOnly": false } }
ng g s shared/push
private subscription: NgPushRegistration;
constructor(private http: Http) { }
subscribeToPush(subscr: NgPushRegistration) {
this.subscription = subscr;
this.http.post(
'http://localhost:3030/webpush',
{ action: 'subscribe', subscription: subscr }
)
.map(res => res.json()).subscribe(data => console.log('--->', data))
}
unsubscribeFromPush() {
this.http.post(
'http://localhost:3030/webpush',
{ action: 'unsubscribe', subscription: this.subscription }
)
.map(res => res.json()).subscribe(data => {
console.log('--->', data);
this.subscription = null;
})
}
sendPush(msg) {
const payload = { 'users': ['ALL'], 'msg': { 'msg': msg } };
return this.http.post( 'http://localhost:3030/msg', payload )
.map(res => res.json())
}
ng g c push
import { NgServiceWorker, NgPushRegistration } from '@angular/service-worker';
...
pubKey = '...';
msg = { title: '', message: '' };
constructor(private sw: NgServiceWorker, private push: PushService) { }
subscribeToPush() {
// Subscribe to Push Notifications
this.sw.registerForPush({ applicationServerKey: this.pubKey })
.subscribe((r: NgPushRegistration) => {
console.log('successfully registered', r);
this.push.subscribeToPush(r)
},
err => {
console.error('error registering for push', err);
});
}
unsubscribeFromPush() {
this.push.unsubscribeFromPush();
}
sendMessage(msg) {
this.push.sendPush(msg).subscribe(data => {
msg = { title: '', message: '' };
})
}
"base-64": "^0.1.0", "body-parser": "^1.16.1", "core-js": "^2.4.1", "cors": "^2.8.1", "cron": "^1.2.1", "express": "^4.14.1", "morgan": "^1.8.1", "web-push": "^3.2.2", "winston": "^2.3.1", "yargs": "^7.0.1"
"scripts": { ... "rest": "bookmonkey-api", "push": "node server.js" },
<p>
push works!
</p>
<button (click)="subscribeToPush()">Subscribe to Push</button>
<button (click)="unsubscribeFromPush()">Unsubscribe from Push</button>
<hr>
<form #form="ngForm" class="form-horizontal" (ngSubmit)="sendMessage(form.value)">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="test" class="form-control" id="title" name="title" required minlength="3" placeholder="Title" [(ngModel)]="msg.title" >
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<input type="test" class="form-control" id="message" name="message" required minlength="5" placeholder="Message" [(ngModel)]="msg.message" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" [disabled]="form.invalid" class="btn btn-default">Send</button>
</div>
</div>
</form>
push
to yourngsw-manifest.json
push
serviceHttp
via DIVAPID
keyspush
componentpush.component
VAPID
key