[英]Angular 2 return data from service is not availabe after RxJs subscribe
[英]Angular 2 return data from RxJs subscribe
我有一个带有身份验证功能的服务 -
authenticate(username: string, password: string) {
let ret;
let packet = JSON.stringify({
username: username,
password: password
});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:5000/api/authenticate/', packet, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => {
// put return data into ret
ret = data.token;
},
err => console.log(err),
() => {
// this works!
console.log(ret);
}
);
// get's returned before I put data into it
return ret;
}
所以如果我调用authenticate函数console.log(authenticate('a', 'b'));
,它记录undefined
因为在订阅函数可以将数据放入其中之前返回ret
变量。 如何从authenticate函数返回http响应数据? 我以前从未对RxJS进行过任何反应式编程,而这正是角度2似乎正在使用的。
PS。 对于像go channel或core.async这样的javascript,有没有像样的CSP解决方案?
我使用Observables和Observers来构建我的解决方案。 由于@Injectable创建了一个单例类,我在其中声明了一个Observable,然后我将其暴露给我的组件。 当我将任何数据放入其中时,所有订阅者都会收到有关该事件的通知。 警告:如果你在zone.js 0.5中使用它,它将无法工作。 适用于0.6。
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
@Injectable()
export class AuthService {
// expose to component
notification$: Observable<Notification>;
private observer: Observer<Notification>;
....
constructor(private http: Http) {
this.notification$ = new Observable(observer => this.observer = observer).share();
}
authenticate({username, password}) {
let packet = JSON.stringify({
username: username,
password: password
});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(`${this.baseUri}/authenticate/`, packet, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => {
if (data.success && data.token) {
this.saveJwt(data.token);
} else {
this.deleteJwt();
}
// put data into observavle
this.observer.next({
message: data.message,
type: data.success
});
},
err => {
// put data into observavle
this.observer.next({
message: 'Error connecting to server',
type: false
})
},
() => {}
);
}
}
export class AuthComponent implements OnInit {
observable: Observable<Notification>;
...
ngOnInit() {
// subscribe to the observable
this.observable = this.authService.notification$;
this.observable.subscribe(
data => {
...
}
)
}
}
您需要直接返回与您的请求对应的observable:
authenticate(username: string, password: string) {
let ret;
let packet = JSON.stringify({
username: username,
password: password
});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/api/authenticate/', packet, {
headers: headers
})
.map(res => res.json());
}
并且authenticate
方法的调用者必须在其上订阅以接收结果:
this.service.authenticate('username', 'password').subscribe(
(result) => {
console.log('Result received');
console.log(result);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.