Cannot pass data with service in angular2

十年热恋 提交于 2020-06-28 04:16:06

问题


PS:

When I talk to my colleague, they told me to get Role's right with once request, if it is not authenticated then reject, else return the data to frond-end. But, I got stuck in use Angular2's Guard.

Apps do:

  1. Access my routes, and Guard prevent it, the Guard send a request to server to check its auth.
  2. Request the server, when server return statue:trueanddata:[somedatas] then set data with module's dataService, and resolve true for canActivate.
  3. Init the target component, in constructor, use dataService to get the meta data.

But, I failed to pass the data from my Guard to Service. I provide them in same module. Here's my code:

Module.ts:

@NgModule({
  declarations: [
    DocsComponent,
    DocsListComponent, // this is the component I will access
    BarButtonsComponent
  ],
  imports: [
    CommonModule,
    DocsRouting,
    // ShareModule
  ],
  providers:[
    DocsGuard,
    DocsDataService // here I provide my dataService that I mentioned before
  ],
  exports: [DocsComponent],
})

routes:

const DOCS_ROUTES:Routes = [
  {path:'',redirectTo:'doclist',pathMatch:'full'},
  {path:'',component:DocsComponent,children:[
    {path:'doclist', component: DocsListComponent}
  ], canActivate:[DocsGuard] } // use `Guard` to prevent it.
];

My dataService.ts:

  private doclist:Doclist[] ; // this

  getData(){
    return this.doclist; 
  }

  setData(obj){
    this.doclist = obj;
  }

  getDocAuth(): Observable<any>{
    let options = new RequestOptions({
      withCredentials:true
    });
    // ...using get request
    return this.http.get(this.docUrl,options)
    // ...and calling .json() on the response to return data
      .map((res:Response) =>res.json())
      //...errors if any
      .catch((error:any) => {
        console.log(error)
      })
  }

Guard.ts:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>{
    let subject = new Subject<boolean>();
    let that = this;
    this.docsDataService.getDocAuth().subscribe(
      res=>{
        if(res.status){
          // Here I want to pass data to my component, I failed.
          that.docsDataService.setData(res.data); 
          subject.next(true);
        }else{
          subject.next(false);
        }
        console.log("next: returning true");
      },
      err => {
        console.log(err);
        subject.next(false);
      }
    );
    return subject.asObservable().first();
  }

Thanks.

======================supplement 2017-02-17 17:34======================

Appmodule routes:

const APP_ROUTERS:Routes = [
  { path:'',component:JwLoginComponent},
  { path:'main',loadChildren:'app/main/main.module#MainModule'},
  { path:'**', component: PageNotFoundComponent }
];

Main routes:

const MAIN_ROUTES : Routes = [
  {path:'main',component:MainComponent,canActivate:[DataGuard]},
  {path:'share',loadChildren:'app/common/share.module#ShareModule'}
];

Share routes:

const SHARE_ROUTES:Routes = [
  {path:'',redirectTo:'docs',pathMatch:'full'},
  {path:'',component: ShareComponent,children:[
    { path:'docs',loadChildren:'app/docs/docs.module#DocsModule'},  
    // Question here: cannot get data from service set in DocsModule, but in MainModule or AppModule as providers.
    { path:'mic',loadChildren:'app/mic/mic.module#MicModule'},
    { path:'user-manage',loadChildren:'app/user-manage/user-manage.module#UserManageModule'},
    { path:'settings',loadChildren:'app/settings/settings.module#SettingsModule'},
    { path:'logs',loadChildren:'app/logs/logs.module#LogsModule'}
  ]},

];

I found I provide the DocService in MainModule or AppModule, I can got data from @mxii code. But, when I set this service into DocsModule or ShareModule, I cannot got data.


回答1:


This demo should help:

@Injectable()
export class DataService {
  public data = new BehaviorSubject<any>(null);

  public setData(data: any) {
    this.data.next(data);
  }
}

@Injectable()
export class AuthService {
  public validate(user, pass): Observable<any> {
    return Observable.of({ test: 'data' }).delay(123);
  }
}

@Injectable()
export class DocsGuard implements CanActivate {

  constructor(private _authService: AuthService, private _dataService: DataService) {}

  canActivate() {
    return this._authService.validate('user', 'pass').map(data => {
      console.log('GUARD: auth data:', data);

      // .. do something ..

      if (!data || data.anyThing === 'anyValue') {
        console.log('GUARD: auth WRONG');
        return false; // not authenticated !
      }

      console.log('GUARD: auth OKAY, set data..');

      this._dataService.setData(data);

      return true;
    })
    .catch(err => {
      console.log(err);
      return Observable.of(false); // protect route !
    });
  }
}

@Component({
  selector: 'my-comp',
  template: `
    {{ _data | async | json }}
  `,
})
export class DocsListComponent {

  private _data: BehaviorSubject<any>;

  constructor(private _dataService: DataService) { }

  ngOnInit() {
    this._data = this._dataService.data;
    this._data.subscribe(data => {
      console.log('DocsListComponent: something changed', data);
    });
  }
}

live demo: https://plnkr.co/edit/PGsTD3Ma9yDidhxEgot3?p=preview

UPDATE

Your Service should only be included ONCE!!

You have to provide your Service to the "highest" NgModule.

Otherwise every NgModule will create a NEW instance of your Service..

If it's only provided to one NgModule, its a singleton!

Maybe you have to create functions like forRoot and forChild like the RouterModule does.



来源:https://stackoverflow.com/questions/42292115/cannot-pass-data-with-service-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!