我试图创建一个可观察的方法,在该方法中我返回一个String值并订阅它,但是在订阅后却没有得到返回的String值。我是Angular的新手
shared / ExamplenService.ts
theEvent(e){
if(e.key === 'Enter') {
this.setState({
newTypePredefinedValue: '',
readOnly:true
});
fetch(..., { ... })
.then(res => {
// Handle response
this.setState({
readOnly:false
})
});
}
}
dashboard / test / TestComponent.ts
@Injectable()
export class ExamplenService {
someValue: any;
public setSomething(){
return return Observable.create(observer => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
this.sameValue=""// Extracting some value from a http call
});
public getSomething(): any {
const studentsObservable = new Observable(observer => {
setTimeout(() => {
observer.next(this.sameValue);
}, 1000);
});
return studentsObservable;
}
export class TestComponent implements OnInit
_data : any;
constructor(private http: Http, private example: ExamplenService) {
}
ngOnInit() {
const s= this.example.getSomething().subscribe((_url :String)=>
{
this._data =_url;
console.log("Rest1"+this._data);//This log is not showing in console
});
}
答案 0 :(得分:0)
之所以得到undefined
是因为您从未设置过该值。函数setSomething()
不会被调用,因此您的变量不会被初始化。
我只是按照相同的方式添加了一个演示。
答案 1 :(得分:0)
您需要初始化'this.samValue =“ hello”'。
ngOnInit() {
this.example.setSomething(); // for initialisation
const s= this.example.getSomething().subscribe((_url :String)=>
{
this._data =_url;
console.log("Rest1"+this._data);//This log is not showing in console
});
}
console.log("Rest2"+this._data);This log is showing Rest2 Udefined