Typescript ionic2-将变量从app.component.ts传递到另一个组件
我正在进行长时间轮询,并从数据库中获取一个值(其值会发生变化),它保存在app.component.ts中名为shareVariable的变量中 我有一个名为header的组件,我想在其中显示这个值。该组件的作用类似于我在每个页面上注入的页面标题。 但是这个值没有被传递 这里是app.component.ts 这是我试图共享的变量Typescript ionic2-将变量从app.component.ts传递到另一个组件,typescript,ionic-framework,ionic2,Typescript,Ionic Framework,Ionic2,我正在进行长时间轮询,并从数据库中获取一个值(其值会发生变化),它保存在app.component.ts中名为shareVariable的变量中 我有一个名为header的组件,我想在其中显示这个值。该组件的作用类似于我在每个页面上注入的页面标题。 但是这个值没有被传递 这里是app.component.ts 这是我试图共享的变量newNotifications import { Component, ViewChild, Input } from '@angular/core'; import
newNotifications
import { Component, ViewChild, Input } from '@angular/core';
import { Events, Nav} from 'ionic-angular';
import * as io from "socket.io-client";
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
socket: any;
newNotifications:number;
constructor(public events: Events) {
this.newNotifications=0;
this.fetchNewNotifications();
}
fetchNewNotifications() {
// create a new websocket
var socket = io.connect('http://localhost:8000');
socket.on('notification', function (data) {
this.newNotifications = data.user_id;
console.log(newNotificationCount);
});
}
}
我的通用标题的代码是:
import { NavController, Events} from 'ionic-angular';
import { Component, Input } from '@angular/core';
@Component({
selector: 'common-header',
templateUrl: `
<div>{{newNotificationCount}}</div>
`
})
export class CommonHeader {
constructor(public navCtrl: NavController, public events: Events) {
}
}
从“离子角度”导入{NavController,Events};
从“@angular/core”导入{Component,Input};
@组成部分({
选择器:“公共标头”,
模板URL:`
{{newNotificationCount}}
`
})
导出类CommonHeader{
构造函数(公共navCtrl:NavController,公共事件:事件){
}
}
我不知道为什么它没有被共享。将变量定义为
CommonHeader
@Input()
newNotificationCount;
并将其传递到app.html-template中:
不清楚您在这两个组件中定义了newNotificationCount
。它编译吗
看起来您需要的是某种全局变量
方法1(最简单):
在一个单独的文件中定义一个变量,然后将其导入到您想要使用它的任何地方。例如:
globals.ts
:
var newNotificationCount = 0;
在其他组成部分:
import {newNotificationCount} from 'globals';
然后你可以在文件的任何地方使用这个变量
方法2:使用Get
和Set
方法生成globals.ts a。这有更好的封装,如果全局变量失控,您可以更好地管理它们
方法3:使用或:如果您希望在全局值更新后立即执行更新视图(如运行函数)以外的操作,则特别推荐使用或