一切都按预期工作,但我无法更新视图。
我希望每次数据流下来时ngOnInit()内的订阅都会更新视图。
但是,当数据沿流传输时,代码this.user = user不会更新视图:(
我的组件代码是...
import {Component, OnInit} from '@angular/core';
import {Subject, Observable} from 'rxjs/Rx';
import {AuthService} from '../../../services/auth.service';
import 'rxjs/add/operator/catch';
declare let auth2:any;
@Component({
selector: 'user',
templateUrl: 'build/routes/app/user/user.component.html',
styleUrls: ['build/routes/app/user/user.component.css'],
providers: [AuthService]
})
export class UserComponent implements OnInit {
private userSubject = new Subject<string>();
public user:any;
public userStream:Observable<any> = this.userSubject.asObservable().flatMap((code:any) => {
let restStream = this.authService.signIn(code)
.map((response:any) => {
return JSON.parse(response._body);
}).catch((err:any) => {
return Observable.throw(err);
});
return restStream;
}).publish().refCount();
constructor(public authService:AuthService) {
}
ngOnInit() {
this.userStream.subscribe((user:any) => {
console.log(user); // user is set
this.user = user; // this does not update the view :(
});
}
public googleSignIn() {
auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then((authResult:any) => {
this.userSubject.next(authResult.code);
});
}
}
视图就是...
<button (click)="googleSignIn()">Google Sign In</button>
<div>USER = {{user | json}}</div>
如何获取Angular2更新视图?
注意:全局声明auth2指的是全局Google OAuth2-谢谢
通过在subscription中添加另一个控制台日志来确认是否设置了this.user。
console.log(this.user);
我认为可以设置,但是UI不更新是您的问题。刚开始时,您可以尝试将用户设置包装为超时,并查看UI更新是否如
setTimeout( user => this.user = user, 0);
如果这样可以使您工作,那么就太早/太晚地设置变量,以至于无法检测到更改。
setTimeout
这不是实现此目标的理想方法,因此我们应该以适当的方式重构代码,以确保angular2变化检测能够吸收变化。如果这样可以帮助您发布有关模板的更多详细信息,或者放一个塞子,我们可以看到有什么更好的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句