如何解决TypeScript中的“无法设置未定义的属性“页面””错误?

时间:2019-07-08 19:53:20

标签: typescript ionic-framework firebase-realtime-database

我想基于已登录的TypeScript中的userType定义某些项目的可见性。但是,当我尝试定义页面时,出现运行时错误,无法设置未定义的属性页。 请帮助我。

我的代码:


    export class MenuPage implements OnInit {
      pages : [];
      value="";

      definepages(){ 
        var pages=[];
        var usersRef = firebase.database().ref().child('Users');
        var userEmail = "";
        var userType = "";
        firebase.auth().onAuthStateChanged(function (user) {
          if (user) {
            console.log(user.email);
            userEmail = user.email;
            //userType = user.userType;
          } else {
            // No user is signed in.
          }
        });

        var counter = 0;
        var currentUserData = {};
        usersRef.once("value", function (snapshot) {
          pages=[];
          snapshot.forEach(function (c) {
            if (userEmail == c.val().email) {
              currentUserData["email"] = userEmail;
              currentUserData["entity"] = c.val().userType;
              if( currentUserData["entity"]== 'Admin')
              {

               this.pages = [
              {
                title:'Home',
                url:'/menu/home',
                display:'false',
                icon:'home'
              },
              {
                title:'Register',
                url:'/menu/register',
                display:'true',
                icon:'create'
              },
              {
                title:'Login',
                url:'/menu/login',
                display:'true',
                icon:'log-in'
              },
              {
                title:'Shop by Brand',
                url:'/menu/brand',
                display:'true',
                icon:'log-in'
              },
              {
                title:'Shop by Category',
                url:'/menu/category',
                display:'true',
                icon:'log-in'
              },
            ];
            }
            else if(currentUserData["entity"]== 'Sakhi')
            {
              this.pages=[
                {
                  title:'My Inventory',
                  url:'/menu/my-inventory',
                  display:'true',
                  icon:'log-in'
                },
                {
                  title:'Contact-Us',
                  url:'/menu/contact',
                  display:'true',
                  icon:'contacts'
                },
              ];
              console.log("hello");
            }     
            }//check user email details

          });

        }
        );
      }
      constructor() { this.pages=[]}

      ngOnInit() {
        this.definepages();
      }

    }

我收到以下错误:

  

错误TypeError:无法设置未定义的属性“页面”       在menu.page.ts:40。

1 个答案:

答案 0 :(得分:0)

这些行位于函数范围pages=[];下,这主要是在给您错误,您可能想用this.pages替换。而且我看到您也在创建var pages局部变量,不确定是否需要,可以将其替换为this.pages = []