Angular 7-服务和订阅

时间:2019-02-18 15:00:53

标签: angular typescript

试图了解Angular 7中的服务和订阅。发布在Udemy论坛上,但被告知在此处询问。

我试图了解服务和订阅的工作方式。这是我的设置-

users.service.ts

getUser(emailAddress: string) {
  return this.getallUsers().allusers.find(u => u.emailaddress === emailAddress);
}

public userSelected = new EventEmitter<string>();

users.component.html

<a [routerLink]="['.']" (click)="onUserSelected(user)"> {{ user.emailaddress }} </a>

users.component.ts

onUserSelected(user: User) {
  this.selectedUser = user;
  this.usersService.userSelected.emit(user.emailaddress);
}

当用户单击链接时,将发出userSelected: string。然后,在另一个组件(在同一页面上)中设置订阅,

export class UserMiniComponent implements OnInit {
  user: User;

  constructor(private usersService: UsersService) { }

  ngOnInit() {
    this.usersService.userSelected.subscribe(
      (email: string) => {
        this.user = this.usersService.getUser(email); // email is caught here correctly
        console.log("");
      }
    );
  }
}

从下图可以看到,订阅已正确触发。但是,不确定在预订块中为何userusersService变量为何处于undefined状态。你知道为什么吗?试图理解这一点让我伤了头。请帮忙!

我想从订阅中正确设置this.user

enter image description here

0 个答案:

没有答案