【发布时间】:2017-11-02 09:23:19
【问题描述】:
我正在尝试在 android 上设置一个非常基本的推送通知示例。我使用 nativescript + typescript(即使代码有点乱,因为我不明白如何在 typescript 中正确重写“var Observable = require("data/observable");”和“viewModel”。代码是基于在这个例子中https://bradmartin.net/2015/12/28/use-google-cloud-messaging-for-push-notifications-with-nativescript/
import { Component } from "@angular/core";
import * as pushPlugin from "nativescript-push-notifications";
var Observable = require("data/observable");
@Component({
selector: "my-app",
template: `
<ActionBar title="My App" icon="" class="action-bar">
</ActionBar>
<StackLayout>
<Label text="Tap the button to trigger the register function." textWrap="true" class=""></Label>
<Button text="REGISTER" (tap)="registerTap()" ></Button>
<label text="Your device id/token:" textWrap="true" ></label>
<TextView text="{{ registrationId }}" class="title" textWrap="true"></TextView>
<Label text="{{ message }}" class="message" textWrap="true" ></Label>
</StackLayout> `
})
export class AppComponent {
// Your TypeScript logic goes here
viewModel = new Observable.Observable({
registrationId: ""
});
pageLoaded(args) {
var page = args.object;
page.bindingContext = this.viewModel;
}
registerTap (args) {
var settings = {
// Android settings
senderID: '0434blablabla', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(message) { // Android: Callback to invoke when a new push is received.
console.log(JSON.stringify(message));
alert(JSON.stringify(message));
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
alert("test");
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
alert('Device registered successfully : ' + token);
this.viewModel.set("regId", token);
},
// Error Callback
function(error){
alert("errore");
console.log(error);
alert(error);
}
);
}
}
当我点击注册按钮时,我收到以下错误:
TypeError:“无法读取未定义的属性‘集’” 我是 Typescript 和通知处理的新手,你能给我一个提示吗?
提前致谢
【问题讨论】:
-
您指的是函数内部的
this,函数从调用者那里接收this上下文。如果您使用的是 Typescript,则可以使用粗箭头表达式。所以不要使用function(token) {...},而是使用token => {...}。这样this上下文指的是正确的位置。 -
谢谢!它解决了我的问题,但我不明白为什么..
-
Typescript 在“转译”成 javascript 时会发挥一些作用。它在后台创建了一个名为
_this的变量,它引用您的实例,并且在您寻址this的任何地方,它都更改为_this。看看生成的 javascript 就可以注意到这一点。 -
啊,我明白了!谢谢!
标签: javascript typescript firebase push-notification nativescript