我正在尝试使用服务来定义多个 View 之间的共享资源客户端
。我首先从索引中选择 client
并进行设置:
itemTapped(event, client) {
this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
.subscribe(
data => {
this.clientService.setClient(data)
this.navCtrl.push(ClientGenericPage, {
client_id: data['id'],
tab: 'profile',
current_user: this.current_user
});
},
err => {
this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
this.clientService.hideLoader()
},
() => this.clientService.hideLoader()
)
}
export class ClientService {
private client = new Subject<any>();
constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {
}
setClient(client) {
this.client.next(client)
}
getClient() {
return this.client.asObservable();
}
get(url, token):Observable<Response> {
let headers = new Headers();
headers.append("authentication", token );
let options = new RequestOptions({ headers: headers });
let final_url = `${this.baseUrl}${url}`
return this.http.get(final_url, options)
.map(this.extractData)
.catch(this.handleError)
}
}
然后我尝试获取刚刚设置的客户端并订阅它,以便我可以检测此 View 及其同级 View 中 client
的更改:
this.clientService.getClient()
.subscribe(
val => {
console.log(val)
this.client = val
},
err => console.log(err),
() => {}
)
但是对 getClient()
的调用永远不会返回错误或任何内容。我的可观察对象做错了什么?
编辑:这是组件:
@Component({
selector: 'page-client-details',
templateUrl: 'client-details.html',
providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
client:any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private filterObject: FilterObject,
public http: Http,
public modalController: ModalController,
private clientService: ClientService,
private app: App
) {
this.clientService.getClient()
.subscribe(
val => {
console.log(val)
this.client = val
},
err => console.log(err),
() => console.log("completed")
)
}
最佳答案
为什么要在组件类中定义ClientService。 ClientService 是相关的单个组件吗?
您需要在app.module.ts中提供ClientService并在组件类中注入(inject)clientservice。如果您在组件中提供 clientservice,它将为组件创建不同的实例
app.module.ts
providers: [ ClientService ],
ClientDetailsPage.ts 删除提供程序:[ ClientService ]
{
constructor(clientService : ClientService ) {
}
}
关于 Angular 2 : Using service to share data between components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44372377/