我正在使用observable来将共享服务中的值共享给其他组件,但是在订购时,该值将变得不确定。当我不使用任何回调函数时,我检查了可观察对象和订阅者是否工作正常,但是当我通过回调函数中的setter方法设置“ this”变量时,此范围似乎已完成,并且订阅者的值显示为未定义...
shared / ExamplenService.ts
@Injectable()
export class ExamplenService {
someValue: any;
public seturl(someUrl:String){
this.url=someUrl;
});
public seturl(){
var that=this;
return return Observable.create(observer => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// Some code
getOtherUrl:function(err, data){ // Call back
console.log("Checkdata"+data.url);// I can see the value here
that.seturl(data.url) // The value is getting set here
}
});
public getSomething(): any {
const studentsObservable = new Observable(observer => {
setTimeout(() => {
observer.next(this.sameValue);
}, 1000);
});
return studentsObservable;
}
dashboard / test / TestComponent.ts
export class TestComponent implements OnInit
_data : any;
constructor(private http: Http, private example: ExamplenService) {
}
ngOnInit() {
const s= this.example.getSomething().subscribe((_url :String)=>
{
console.log("Rest1"+_url);//This log is showing undefined)
this._data =_url;
console.log("Rest2"+this._data);//This log is showing undefined)
});
}
答案 0 :(得分:0)
不确定,请尝试以下操作:
ngOnInit() {
const s = this.example.getSomething().subscribe((_url: String) => {
if (_url) {
console.log("Rest1" + _url);
this._data = _url;
console.log("Rest2" + this._data);
}
});
}