Angular 为什么我没有得到任何数据?Ngrx

Angular 为什么我没有得到任何数据?Ngrx,angular,typescript,web,frontend,ngrx,Angular,Typescript,Web,Frontend,Ngrx,我试图在Angular应用程序中实现Ngrx,但遗憾的是无法检索任何数据。感谢您的帮助 我试图在property.component.ts中做的是在组件实例化时获取所有数据,并在property.component.html中显示数据 property.component.ts import {Component, OnInit} from '@angular/core'; import {select, Store} from '@ngrx/store'; import {Router} f

我试图在Angular应用程序中实现Ngrx,但遗憾的是无法检索任何数据。感谢您的帮助

我试图在property.component.ts中做的是在组件实例化时获取所有数据,并在
property.component.html
中显示数据

property.component.ts

import {Component, OnInit} from '@angular/core';
import {select, Store} from '@ngrx/store';

import {Router} from '@angular/router';

@Component({
  selector: 'app-property',
  templateUrl: './property.component.html',
  styleUrls: ['./property.component.css']
})
export class PropertyComponent implements OnInit {

  properties$ = this._store.pipe(select('properties'));

  constructor(private _store: Store<any>, private _router: Router) {}

  ngOnInit() {
    this._store.dispatch({
      type: '[Property] Get Properties'
    });
    console.log(this.properties$);
  }

  navigateToProperty(id: number) {
    this._router.navigate(['property', id]);
  }

}
    import { Injectable } from '@angular/core';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    import { Observable } from 'rxjs';
    import {PropertyModel} from '../models/property.model';

    @Injectable({
      providedIn: 'root'
    })
    export class PropertyService {
      propertiesUrl = 'someapi';
      private httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      constructor(private http: HttpClient) { }

      getProperties(): Observable<PropertyModel[]> {
        return this.http.get<PropertyModel[]>(this.propertiesUrl, this.httpOptions);
      }
    }
import { Action } from '@ngrx/store';
import {PropertyModel} from '../../models/property.model';


export const GET_PROPERTIES = '[Property] Get Properties';
export const GET_PROPERTIES_SUCCESS = '[Property] Get Properties Success';
export const SEARCH_PROPERTY = '[Property] Get Property';
export const SEARCH_PROPERTY_SUCCESS = '[Property] Get Property Success';

export class GetProperties implements Action {
  public readonly type = GET_PROPERTIES;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetPropertiesSuccess implements Action {
  public readonly type = GET_PROPERTIES_SUCCESS;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetProperty implements Action {
  public readonly type = SEARCH_PROPERTY;
  constructor(public searchId: string) {}
}

export type PropertyActions = GetProperties | GetPropertiesSuccess | GetProperty;
import {Injectable} from '@angular/core';
import {Actions, Effect, ofType} from '@ngrx/effects';

import {GET_PROPERTIES, PropertyActions} from '../actions/property.actions';
import {PropertyService} from '../../services/property.service';
import {mapTo} from 'rxjs/operators';


@Injectable()

export class PropertyEffects {

  @Effect()
  getProperties$ = this.actions$.pipe(
    ofType<PropertyActions>(GET_PROPERTIES),
    mapTo(this.propertyService.getProperties())
  );

  constructor(private actions$: Actions, private propertyService: PropertyService) {}

}
import {GET_PROPERTIES, GET_PROPERTIES_SUCCESS, PropertyActions} from '../actions/property.actions';
import {PropertyModel} from '../../models/property.model';

export function propertyReducer(properties: PropertyModel[] = [], action: PropertyActions): PropertyModel[] {
  switch (action.type) {
    case GET_PROPERTIES: {
      return [...action.retrievedProperties];
    }
    default: {
      return properties;
    }
  }
}
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {CustomerComponent} from './customer/customer.component';
import {HttpClientModule} from '@angular/common/http';
import {CustomMaterialModule} from './custom.material.module';
import {RouterModule, Routes} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {StoreModule} from '@ngrx/store';
import {PropertyComponent} from './property/property.component';
import {propertyReducer} from './store/reducers/property.reducers';

const appRoutes: Routes = [
  {
    path: 'customers',
    component: CustomerComponent,
    data: {title: 'Customer List'}
  },
  {
    path: 'property',
    component: PropertyComponent,
    data: {title: 'Property List'}
  },
  {
    path: '', // General redirect
    component: CustomerComponent,
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent,
    PropertyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    BrowserAnimationsModule,
    CustomMaterialModule,
    StoreModule.forRoot(propertyReducer)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
property.service.ts

import {Component, OnInit} from '@angular/core';
import {select, Store} from '@ngrx/store';

import {Router} from '@angular/router';

@Component({
  selector: 'app-property',
  templateUrl: './property.component.html',
  styleUrls: ['./property.component.css']
})
export class PropertyComponent implements OnInit {

  properties$ = this._store.pipe(select('properties'));

  constructor(private _store: Store<any>, private _router: Router) {}

  ngOnInit() {
    this._store.dispatch({
      type: '[Property] Get Properties'
    });
    console.log(this.properties$);
  }

  navigateToProperty(id: number) {
    this._router.navigate(['property', id]);
  }

}
    import { Injectable } from '@angular/core';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    import { Observable } from 'rxjs';
    import {PropertyModel} from '../models/property.model';

    @Injectable({
      providedIn: 'root'
    })
    export class PropertyService {
      propertiesUrl = 'someapi';
      private httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      constructor(private http: HttpClient) { }

      getProperties(): Observable<PropertyModel[]> {
        return this.http.get<PropertyModel[]>(this.propertiesUrl, this.httpOptions);
      }
    }
import { Action } from '@ngrx/store';
import {PropertyModel} from '../../models/property.model';


export const GET_PROPERTIES = '[Property] Get Properties';
export const GET_PROPERTIES_SUCCESS = '[Property] Get Properties Success';
export const SEARCH_PROPERTY = '[Property] Get Property';
export const SEARCH_PROPERTY_SUCCESS = '[Property] Get Property Success';

export class GetProperties implements Action {
  public readonly type = GET_PROPERTIES;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetPropertiesSuccess implements Action {
  public readonly type = GET_PROPERTIES_SUCCESS;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetProperty implements Action {
  public readonly type = SEARCH_PROPERTY;
  constructor(public searchId: string) {}
}

export type PropertyActions = GetProperties | GetPropertiesSuccess | GetProperty;
import {Injectable} from '@angular/core';
import {Actions, Effect, ofType} from '@ngrx/effects';

import {GET_PROPERTIES, PropertyActions} from '../actions/property.actions';
import {PropertyService} from '../../services/property.service';
import {mapTo} from 'rxjs/operators';


@Injectable()

export class PropertyEffects {

  @Effect()
  getProperties$ = this.actions$.pipe(
    ofType<PropertyActions>(GET_PROPERTIES),
    mapTo(this.propertyService.getProperties())
  );

  constructor(private actions$: Actions, private propertyService: PropertyService) {}

}
import {GET_PROPERTIES, GET_PROPERTIES_SUCCESS, PropertyActions} from '../actions/property.actions';
import {PropertyModel} from '../../models/property.model';

export function propertyReducer(properties: PropertyModel[] = [], action: PropertyActions): PropertyModel[] {
  switch (action.type) {
    case GET_PROPERTIES: {
      return [...action.retrievedProperties];
    }
    default: {
      return properties;
    }
  }
}
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {CustomerComponent} from './customer/customer.component';
import {HttpClientModule} from '@angular/common/http';
import {CustomMaterialModule} from './custom.material.module';
import {RouterModule, Routes} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {StoreModule} from '@ngrx/store';
import {PropertyComponent} from './property/property.component';
import {propertyReducer} from './store/reducers/property.reducers';

const appRoutes: Routes = [
  {
    path: 'customers',
    component: CustomerComponent,
    data: {title: 'Customer List'}
  },
  {
    path: 'property',
    component: PropertyComponent,
    data: {title: 'Property List'}
  },
  {
    path: '', // General redirect
    component: CustomerComponent,
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent,
    PropertyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    BrowserAnimationsModule,
    CustomMaterialModule,
    StoreModule.forRoot(propertyReducer)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
property.effects.ts

import {Component, OnInit} from '@angular/core';
import {select, Store} from '@ngrx/store';

import {Router} from '@angular/router';

@Component({
  selector: 'app-property',
  templateUrl: './property.component.html',
  styleUrls: ['./property.component.css']
})
export class PropertyComponent implements OnInit {

  properties$ = this._store.pipe(select('properties'));

  constructor(private _store: Store<any>, private _router: Router) {}

  ngOnInit() {
    this._store.dispatch({
      type: '[Property] Get Properties'
    });
    console.log(this.properties$);
  }

  navigateToProperty(id: number) {
    this._router.navigate(['property', id]);
  }

}
    import { Injectable } from '@angular/core';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    import { Observable } from 'rxjs';
    import {PropertyModel} from '../models/property.model';

    @Injectable({
      providedIn: 'root'
    })
    export class PropertyService {
      propertiesUrl = 'someapi';
      private httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      constructor(private http: HttpClient) { }

      getProperties(): Observable<PropertyModel[]> {
        return this.http.get<PropertyModel[]>(this.propertiesUrl, this.httpOptions);
      }
    }
import { Action } from '@ngrx/store';
import {PropertyModel} from '../../models/property.model';


export const GET_PROPERTIES = '[Property] Get Properties';
export const GET_PROPERTIES_SUCCESS = '[Property] Get Properties Success';
export const SEARCH_PROPERTY = '[Property] Get Property';
export const SEARCH_PROPERTY_SUCCESS = '[Property] Get Property Success';

export class GetProperties implements Action {
  public readonly type = GET_PROPERTIES;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetPropertiesSuccess implements Action {
  public readonly type = GET_PROPERTIES_SUCCESS;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetProperty implements Action {
  public readonly type = SEARCH_PROPERTY;
  constructor(public searchId: string) {}
}

export type PropertyActions = GetProperties | GetPropertiesSuccess | GetProperty;
import {Injectable} from '@angular/core';
import {Actions, Effect, ofType} from '@ngrx/effects';

import {GET_PROPERTIES, PropertyActions} from '../actions/property.actions';
import {PropertyService} from '../../services/property.service';
import {mapTo} from 'rxjs/operators';


@Injectable()

export class PropertyEffects {

  @Effect()
  getProperties$ = this.actions$.pipe(
    ofType<PropertyActions>(GET_PROPERTIES),
    mapTo(this.propertyService.getProperties())
  );

  constructor(private actions$: Actions, private propertyService: PropertyService) {}

}
import {GET_PROPERTIES, GET_PROPERTIES_SUCCESS, PropertyActions} from '../actions/property.actions';
import {PropertyModel} from '../../models/property.model';

export function propertyReducer(properties: PropertyModel[] = [], action: PropertyActions): PropertyModel[] {
  switch (action.type) {
    case GET_PROPERTIES: {
      return [...action.retrievedProperties];
    }
    default: {
      return properties;
    }
  }
}
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {CustomerComponent} from './customer/customer.component';
import {HttpClientModule} from '@angular/common/http';
import {CustomMaterialModule} from './custom.material.module';
import {RouterModule, Routes} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {StoreModule} from '@ngrx/store';
import {PropertyComponent} from './property/property.component';
import {propertyReducer} from './store/reducers/property.reducers';

const appRoutes: Routes = [
  {
    path: 'customers',
    component: CustomerComponent,
    data: {title: 'Customer List'}
  },
  {
    path: 'property',
    component: PropertyComponent,
    data: {title: 'Property List'}
  },
  {
    path: '', // General redirect
    component: CustomerComponent,
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent,
    PropertyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    BrowserAnimationsModule,
    CustomMaterialModule,
    StoreModule.forRoot(propertyReducer)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
app.module.ts

import {Component, OnInit} from '@angular/core';
import {select, Store} from '@ngrx/store';

import {Router} from '@angular/router';

@Component({
  selector: 'app-property',
  templateUrl: './property.component.html',
  styleUrls: ['./property.component.css']
})
export class PropertyComponent implements OnInit {

  properties$ = this._store.pipe(select('properties'));

  constructor(private _store: Store<any>, private _router: Router) {}

  ngOnInit() {
    this._store.dispatch({
      type: '[Property] Get Properties'
    });
    console.log(this.properties$);
  }

  navigateToProperty(id: number) {
    this._router.navigate(['property', id]);
  }

}
    import { Injectable } from '@angular/core';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    import { Observable } from 'rxjs';
    import {PropertyModel} from '../models/property.model';

    @Injectable({
      providedIn: 'root'
    })
    export class PropertyService {
      propertiesUrl = 'someapi';
      private httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      constructor(private http: HttpClient) { }

      getProperties(): Observable<PropertyModel[]> {
        return this.http.get<PropertyModel[]>(this.propertiesUrl, this.httpOptions);
      }
    }
import { Action } from '@ngrx/store';
import {PropertyModel} from '../../models/property.model';


export const GET_PROPERTIES = '[Property] Get Properties';
export const GET_PROPERTIES_SUCCESS = '[Property] Get Properties Success';
export const SEARCH_PROPERTY = '[Property] Get Property';
export const SEARCH_PROPERTY_SUCCESS = '[Property] Get Property Success';

export class GetProperties implements Action {
  public readonly type = GET_PROPERTIES;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetPropertiesSuccess implements Action {
  public readonly type = GET_PROPERTIES_SUCCESS;
  constructor(public retrievedProperties: PropertyModel[]) {}
}

export class GetProperty implements Action {
  public readonly type = SEARCH_PROPERTY;
  constructor(public searchId: string) {}
}

export type PropertyActions = GetProperties | GetPropertiesSuccess | GetProperty;
import {Injectable} from '@angular/core';
import {Actions, Effect, ofType} from '@ngrx/effects';

import {GET_PROPERTIES, PropertyActions} from '../actions/property.actions';
import {PropertyService} from '../../services/property.service';
import {mapTo} from 'rxjs/operators';


@Injectable()

export class PropertyEffects {

  @Effect()
  getProperties$ = this.actions$.pipe(
    ofType<PropertyActions>(GET_PROPERTIES),
    mapTo(this.propertyService.getProperties())
  );

  constructor(private actions$: Actions, private propertyService: PropertyService) {}

}
import {GET_PROPERTIES, GET_PROPERTIES_SUCCESS, PropertyActions} from '../actions/property.actions';
import {PropertyModel} from '../../models/property.model';

export function propertyReducer(properties: PropertyModel[] = [], action: PropertyActions): PropertyModel[] {
  switch (action.type) {
    case GET_PROPERTIES: {
      return [...action.retrievedProperties];
    }
    default: {
      return properties;
    }
  }
}
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {CustomerComponent} from './customer/customer.component';
import {HttpClientModule} from '@angular/common/http';
import {CustomMaterialModule} from './custom.material.module';
import {RouterModule, Routes} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {StoreModule} from '@ngrx/store';
import {PropertyComponent} from './property/property.component';
import {propertyReducer} from './store/reducers/property.reducers';

const appRoutes: Routes = [
  {
    path: 'customers',
    component: CustomerComponent,
    data: {title: 'Customer List'}
  },
  {
    path: 'property',
    component: PropertyComponent,
    data: {title: 'Property List'}
  },
  {
    path: '', // General redirect
    component: CustomerComponent,
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    CustomerComponent,
    PropertyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
    BrowserAnimationsModule,
    CustomMaterialModule,
    StoreModule.forRoot(propertyReducer)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
工作

不要忘记分派成功和错误操作,并减少它们。 同时将
mapTo
更改为
switchMapTo

@Effect()
getProperties$ = this.actions$.pipe(
  ofType<PropertyActions>(GET_PROPERTIES),
  switchMapTo(this.propertyService.getProperties().pipe(
    map(props => new GetPropertiesSuccess(props)),
   // catch error here
   // catchError(error => of(new GetPropertiesError(error))),
    ),
  ),

);
为清晰起见,请从
GetProperties
中删除
retrievedProperties
——该操作没有任何检索到的道具。成功的行动应该用来通过它们

在应用程序模块中,更改减速器设置,不要忘记导入效果:

imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
HttpClientModule,
BrowserAnimationsModule,
// change this
StoreModule.forRoot({properties: propertyReducer}),
// this is needed
EffectsModule.forRoot([PropertyEffects])
],
可选:在
PropertyComponent
中,将调度的操作更改为
GetProperties
类的实例。这就是它应该被使用的方式

 this._store.dispatch(new GetProperties());

您的效果应该发送成功,然后将返回的数据映射到您的状态。现在,您正在调用服务,但返回的数据没有映射到您的状态,因为在生效之前调用了reducer。如何在生效之前调用我的reducer?我尝试了您的代码,但localhost似乎只是不断加载。如果不实际运行它,很难调试整个代码。如果您提供一个stackblitz示例,我会看一看。我还添加了一个东西,
app.module.ts
,如果这有帮助的话。我会尝试设置一个stackblitz,同时,我会去兔子洞。你的代码中有越来越多的错误。你应该去试试NGRx教程。这里有很多误解,我有办法做到。我扩展了我的答案,所以它包含了一切。祝你好运。