我正在尝试使用服务在多个视图之间定义共享资源client
。我首先从索引中选择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)
}
}
然后我尝试获取刚设置的客户端并订阅它,以便我可以检测此视图及其兄弟姐妹中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")
)
}
答案 0 :(得分:3)
为什么要在组件类中定义ClientService。是ClientService相关的单个组件吗?
您需要在app.module.ts中提供ClientService并在组件类中注入clientservice。如果您在组件中提供客户端服务,它将为组件
创建不同的实例app.module.ts
providers: [ ClientService ],
ClientDetailsPage.ts 删除提供商:[ClientService]
{
constructor(clientService : ClientService ) {
}
}
答案 1 :(得分:0)
您可以尝试使用BehaviorSubject而不是Subject,您需要的唯一更改提供默认值。我修复了相同的错误,但没有发现问题。