我在两个组件之间的观察服务方法中苦苦挣扎。我有一个包含设置组件的配置文件组件。两者都使用 user.service,其中提供者在 app.module.ts 中定义。提供者未在其他任何地方定义。因此,当我在 settings.component 上更改例如 firstName 并保存它时。在我重新加载页面之前,更改不会反映在 profile.component 侧边栏中。
下班后: 我找到了一个解决方案,可以在更新发生后立即触发的事件发射器上执行此操作。这将解决我上面的问题,但我认为这不是正确的方法,因为我阅读了下面的文章:
如果没有事件发射器,它不应该工作吗?
所以我的问题是: 你会在这种情况下使用什么方法或者最好的做法是什么?当然,我的代码中可能存在问题。我真的很陌生。
app.module.ts
在我定义的 app.module.ts 中:
providers: [UserService]
profile.component.ts
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: any;
Role = Role;
constructor(private _userService: UserService, ) { }
ngOnInit() {
const token = localStorage.getItem('token');
const role = jwt.decode(token).user.role;
this._userService.getUser().subscribe(v => { this.user = v; });
// Event Emmiter Subscription
this._userService.change.subscribe(v => { this.user = v; });
}
}
profile.component.html
<div *ngIf="user" class="container mt50">
<div class="row profile">
<div class="col-md-3">
<div class="profile-sidebar">
<!-- SIDEBAR USERPIC -->
<div class="profile-userpic">
<img gravatar [email]="user.email" [size]="256" class="img-responsive animated bounceIn" alt="">
</div>
<!-- END SIDEBAR USERPIC -->
<!-- SIDEBAR USER TITLE -->
<div class="profile-usertitle">
<div class="profile-usertitle-name">
{{ user.firstName }} {{ user.lastName }}
</div>
<div class="profile-usertitle-job">
{{ user.email }}
</div>
</div>
</div>
</div>
<div class="col-md-9">
<app-profile-settings-admin *ngIf="user.role === Role.ADMINISTRATOR"></app-profile-settings-admin>
</div>
</div>
</div>
用户服务.ts
@Injectable()
export class UserService {
public user: any;
constructor(private http: Http) { }
// EVENT EMIITER
public change: EventEmitter<any> = new EventEmitter();
getUser() {
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.get('api/user' + token)
.map((response: Response) => {
this.user = response.json().obj;
return this.user;
})
.catch((error: Response) => Observable.throw(error.json()));
}
updateUser(user) {
const body = JSON.stringify(user);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch('api/user/' + token, body, {headers: headers})
.map((response: Response) => {
const result = response.json();
this.user = result.obj;
// EMIT EVENT
this.change.emit(this.user);
return this.user;
})
.catch((error: Response) => Observable.throw(error.json()));
}
}
profile.settings.admin.component.ts
在该组件中,只有一个表单会在提交时触发以下代码:
onSubmit() {
this._userService.updateUser(this.userForm.value)
.subscribe(
data => {
this._toastyService.default('Settings saved!');
console.log(data);
},
error =>{
this._toastyService.default('Error occured!');
console.log(error);
}
);
}