定义服务属性并在组件

时间:2017-09-01 19:06:08

标签: javascript angular typescript angularfire2

不确定如何从admin访问AuthService属性。组件中的完全相同的代码将this.admin设置为数据库中的值,但我不想重写每个组件中的代码。

@Injectable()
export class AuthService {

public admin: any;

constructor() {
    this.currentUser.take(1).subscribe(user => {
          if (user) {
            this.db.object(`/users/${user.uid}`).subscribe(usr => this.setAdmin(usr));
          }
        });
    }
}


setAdmin(usr) {
    console.log(usr.admin); // returns value from database
    this.admin = usr.admin;
    console.log(this.admin); // returns usr.admin value
}

成分<​​/ P>

export class AppComponent implements OnInit {
    public isA: any;


  constructor(public authService: AuthService,){

  }

  ngOnInit() {
    this.isA = this.authService.admin; // this is undefined
  }
}

组件编辑*****

  ngOnInit() {
    this.msgService.getPermission();
    this.msgService.receiveMessage();
    this.message = this.msgService.currentMessage;
      this.authService.currentUser.take(1).subscribe(user => {
        if (user) {
          console.log(user.uid);
          this.db.object(`/users/${user.uid}`).subscribe(usr => this.setAdmin(usr))
        }
      });
  }

  setAdmin(usr) {
    this.admin = usr.admin;
  }

1 个答案:

答案 0 :(得分:0)

首先,您需要在服务上使用get方法。其次,在不知道它何时会出现的情况下访问一个值是很棘手的(ASYNC,不会立即返回,也不会停止代码。像PHP一样)。 因此,您可以选择使用.subscribe ()方法中的值来包装您想要执行的操作,或让ngDoCheck (){}持续监控更改,并在值存在时拾取(我不建议)这种方法,因为它运行任何变化)。或者我更喜欢将事物设为BehaviourSubject,以便它可以作为Observable使用,并且Subscribe可以使用它,这样当值发生变化时,组件会自动拾取它。

&#13;
&#13;
@Injectable()
export class AuthService {

  public admin: BehaviourSubject < any > = new BehaviourSubject(null);

  constructor() {
    this.currentUser.take(1).subscribe(user => {
      if (user) {
        this.db.object(`/users/${user.uid}`).subscribe(usr => this.setAdmin(usr));
      }
    });
  }
}


setAdmin(usr) {
  console.log(usr.admin); // returns value from database
  this.admin.next (usr.admin);
  console.log(this.admin); // returns usr.admin value
}

getAdmin(): Observable < any > {
  return this.admin.asObservable();
}
&#13;
&#13;
&#13;

&#13;
&#13;
export class AppComponent implements OnInit {
  public isA: any;


  constructor(public authService: AuthService, ) {

  }

  ngOnInit() {
    this.authService.getAdmin.subscribe((admin: any) => {
      //Anything in here get executed every time the `admin` variable's value chnages
    });
  }

  // If you want to see how the ngDocheck() behave
  ngDoCheck() {
    console.log("DoCheck");
  }
}
&#13;
&#13;
&#13;