这是页面上的功能
this.productProvider.getproductlist().subscribe(res => {
console.log(res);
}, error => {
console.log(error);
});
这是我的提供商中的功能
getproductlist(){
this.storage.get('token').then((val) => {
return this.http.get(this.baseAppUrl+'/getproductlist?token='+val);
});
}
错误: 类型为void
的属性订阅不存在如果我试试这个
this.storage.get('token').then((val) => {
this.token = val;
});
return this.http.get(this.baseAppUrl+'/getproductlist?token='+this.token);
我不会在类型void error上存在属性subscribe,但令牌值为null。
答案 0 :(得分:2)
尝试此代码使用mergeMap和fromPromise(从promise创建observable)来自rxjs库:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';
getproductlist(): Observable<any> {
return Observable.fromPromise(this.storage.get('token')).mergeMap((val) => {
return this.http.get(this.baseAppUrl+'/getproductlist?token='+val);
});
}
答案 1 :(得分:0)
当我通过服务实现组件交互时,我使用Observer模式,在这种情况下,服务实例的范围是来自组件(Publisher)和其他组件(订阅者)的通知。
<强> mycomponent.service.ts 强>
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyComponentService{
// Observable
private sampleObservable = new Subject<boolean>();
// Observable boolean streams
sampleSubscriber = this.sampleObservable.asObservable();
// Event for notification from publisher to subscriber
sampleEventChanged(value:boolean)
{
this.sampleObservable.next();
}
}
在想要通知所有订户状态更改的组件中:
<强> myComponent的-publisher.ts 强>
import { Component } from '@angular/core';
import { MyService } from './mycomponent.service';
@Component({
selector: 'app-my-control-publisher',
template: `
<h2>This is the publisher control</h2>
<button (click)="announce()">Announce to subscriber</button>
`,
providers: [MyService]
})
export class MyControlPublisherComponent
{
constructor(private myService: MyService) { }
announce()
{
this.myService.sampleEventChanged(true);
}
}
在想要获取通知的订阅者组件中。
<强> myComponent的-subscriber.ts 强>
import { Component, OnDestroy } from '@angular/core';
import { MyService } from './mycomponent.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-my-control-subscriber',
template: `
<h2>This is the subscriber control</h2>
`,
})
export class MyControlSubscriberComponent
{
// Subscriptions
private componentSubscription: Subscription;
constructor(private myService: MyService)
{
// Subscription of the notifications
this.componentSubscription= this.myService.sampleSubscriber.subscribe(value =>
{
// Put the code for manage the notification here
}
}
ngOnDestroy()
{
// Release subscription to avoid memory leaks when the component is destroyed
this.componentSubscription.unsubscribe();
}
}
在您的情况下,getproductlist应声明为observable
// Observable resources
private getProductListObservable = new Subject<any>();
// Observable streams
getproductlistSubscriber = this.getProductListObservable.asObservable();
getproductlist ()
{
this.getProductListObservable.next(this.http.get(this.baseAppUrl+'/getproductlist?token='+val));
}