如何在subscribe()中访问此属性?

时间:2017-07-20 14:47:44

标签: angular angular2-services

我在组件中有属性:

public _flashMessagesService: FlashMessagesService;

以下代码:

return this.http.get(this.apiUrl.base_path + 'credentials')
      .map(res => res.json())
      .subscribe(
        credentials => {
          console.log(this._flashMessagesService);
          this._flashMessagesService.show('We are in about component!', { cssClass: 'alert-success', timeout: 1000 });
          this.saveToken(credentials);
        },
        err => {
          this._flashMessagesService.show('We are in about component!' + err, { cssClass: 'alert-error', timeout: 1000 });
          }
      );

我无法访问this._flashMessagesService.show

1 个答案:

答案 0 :(得分:1)

在与作者讨论时发现了决议:

  1. _flashMessageService无法正常使用(我们没有找到原因)。
  2. 它在组件内部正常工作。
  3. 我们所做的是将_flashService登录到组件:

    Service.ts:

    @Injectable()
    export class SomeService {
        constructor(private http: Http){}
        public login(user, pass): Observable<Response> {
            return this.http.get("someUrl");
        }
    }
    

    Component.ts:

    @Component({
         //some component setup
    })
    export class MyComponent{
        constructor(private _flashMessagesService: FlashMessagesService, private service: SomeService)
    
        public method():void {
            this.service.login("aaa","bbb").map(res => res.json())
            .subscribe( credentials => {
                this._flashMessagesService.show('We are in about component!', { cssClass: 'alert-success', timeout: 1000 });
                this.saveToken(credentials);
            }, err => {
                this._flashMessagesService.show('We are in about component!' + err, { cssClass: 'alert-error', timeout: 1000 });
            });
        }
    }