[英]How to update parent's variable in child component after child has called parents function that has http request
I cannot seem to see the changed @Input in the child component after it was updated in parents http request. 在父级HTTP请求中更新子组件后,我似乎看不到已更改的@Input。
This is an example: 这是一个例子:
Parent 父级
import { ChildComp } from './child.component';
@Component({
template: <child [counter]="a" [updateCounter]="updateCounter"></child>,
directives: [ChildComp]
})
export class ParentComponent {
public a = 1;
public CallBack:Function;
constructor(private _http:Http) {}
public ngOnInit() {
this.CallBack = this.updateCounter.bind(this);
}
public updateCounter() {
this._http.get('/newcounter/').subscribe(
data => {
// update counter
this.a = JSON.parse(data['_body']);
},
error => {},
() => console.log('updated counter')
);
}
}
Child 儿童
@Component({
selector: 'child',
template: `
<button class="btn btn-default" (click)="updateCounter()"></button>
<p>counter: {{ counter }}</p>
`,
inputs: ["counter", "updateCounter"]
})
export class ChildComponent {
public counter;
public updateCounter:Function;
constructor() {}
}
So, this works if there is not http request. 因此,如果没有http请求,这将起作用。 But once I have the request, the child view will not update the counter .
但是,一旦收到请求,子视图将不会更新计数器 。
Any ideas? 有任何想法吗? What am I missing?
我想念什么?
One hack i have now is to setTimeout
on child component to update the counter 500ms after the call to updateCounter
我现在有一个办法是在调用
updateCounter
之后500ms上对子组件设置setTimeout
来更新计数器
Amend the updateCounter
function of your parent component like this: 修改父组件的
updateCounter
函数,如下所示:
public updateCounter() {
let that = this;
this._http.get('/newcounter/').subscribe(
data => {
// update counter
that.a = JSON.parse(data['_body']);
},
error => {},
() => console.log('updated counter')
);
}
Using this
in the promise does not reference your class anymore. 使用
this
在承诺不引用你的类了。 So you need to keep a reference to this
in another variable and use that one instead. 因此,您需要在另一个变量中保留
this
的引用,并改用该变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.