简体   繁体   English

从发布请求Angular / .NET Core获取数据

[英]Get Data From Post Request Angular/.NET Core

I'm having trouble getting a JSON response from a POST Request from my .Net Core server. 我无法从.Net Core服务器的POST请求中获取JSON响应。 In essence I would be using this POST request like a GET request from the server. 本质上,我将像服务器的GET请求一样使用此POST请求。 I believe I'm passing in the correct headers, however, in my console error I'm getting 我相信我传递的是正确的标题,但是,在控制台错误中,我得到了

ERROR TypeError: Cannot read property 'sessionId' of undefined 错误TypeError:无法读取未定义的属性'sessionId'

I suspect it's something that has to do with the type and/or model. 我怀疑这与类型和/或模型有关。 Or possibly how I'm calling it in the service. 或者可能是我在服务中如何称呼它。 If I need to add anything for clarification, lmk. 如果我需要添加任何内容进行澄清,lmk。

.NET CORE Server Code .NET CORE服务器代码

Action.Dto 动作

{
public class ActionDto
{
    public string SessionId { get; set; }
    public Tag ActionTag { get; set; }
    public ActionParams Args { get; set; }
}

} }

ActionService.cs ActionService.cs

    {
    ActionResponse LaunchAction(string sessionId, Tag actionTag, ActionParams args, UserState userState);
}

Action Controller 动作控制器

 public IActionResult LaunchAction([FromBody]ActionDto launchActionParameters)
    {
        var sessionId = launchActionParameters.SessionId;
        var actionTag = launchActionParameters.ActionTag;
        var args = launchActionParameters.Args;
        UserState userState = null;
        RunAction runAction = null;

Angular Client Code Angular客户端代码

Action Component 动作组件

       export interface ActionView {
  actionName: string;
  actionType: string;
  primaryTable: string;
  specialUse: string;
  folder: string;
  actionDescription: string;
  actionTag: number;
  chartType: string;
  priority: number;
}

const ACTION_DATA: ActionView[] = [];

@Component({
  templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {

    // User Fields
    currentUser: User;
    users: User[] = [];
    currentUserSubscription: Subscription;

    // Action Fields
    currentAction: Action;
    actions: Action[]  = [];


    displayedColumns: string[] =
    ['actionName', 'actionType', 'primaryTable', 'specialUse',
    'folder', 'actionDescription', 'actionTag', 'chartType',
     'priority'];

    dataSource: any = new MatTableDataSource(ACTION_DATA);

    constructor(
        private authenticationService: AuthenticationService,
        private iconRegistry: MatIconRegistry,
        private sanitizer: DomSanitizer,
        private httpClient: HttpClient,
        private actionService: ActionService
    ) {
        this.currentUserSubscription = this.authenticationService.currentUser.subscribe(user => {
            this.currentUser = user;
        });
        this.iconRegistry.addSvgIcon(
          'thumbs-up',
         this.sanitizer.bypassSecurityTrustResourceUrl('assets/img/examples/thumbup-icon.svg'));
    }

    @ViewChild(MatSort) sort: MatSort;

   public getActions() {
      console.log('test');

      this.actionService.getActions(
        this.currentAction).subscribe((data) => {
          this.dataSource = data;
        });
    }

    ngOnInit() {
      this.dataSource.sort = this.sort;
      this.getActions();
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.currentUserSubscription.unsubscribe();
    }
}

Action Service 行动服务

@Injectable({ providedIn: 'root' })
export class ActionService {

  public apiURL = 'http://localhost:15217/api';
  public currentUser: Observable<User>;
  public currentAction: Observable<Action>;

    constructor(private http: HttpClient) { }
      // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  getActions(action: Action): Observable<Action[]> {
    return this.http.post<Action[]>(this.apiURL + '/actions/launchactions',
    {
        sessionId: action.sessionId,
        tag: action.actionTag,
        actionParams: action.actionParams
     })
    .pipe(
      retry(1),
      catchError(this.handleError)
    );
  }

    // Error handling
    handleError(error: any) {
      let errorMessage = '';
      if (error.error instanceof ErrorEvent) {
        // Get client-side error
        errorMessage = error.error.message;
      } else {
        // Get server-side error
        errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
      }
      window.alert(errorMessage);
      return throwError(errorMessage);
   }

add [FromBody] to controller side service, before the parameter. 在参数之前将[FromBody]添加到控制器端服务。 Post method pass parameters in body. Post方法在主体中传递参数。

like 喜欢

ActionResponse LaunchAction([FromBody]string sessionId, [FromBody]Tag actionTag, [FromBody]ActionParams args, [FromBody]UserState userState);

I don't know why microsoft did not decide to do this default. 我不知道为什么微软没有决定执行此默认设置。

您应该从数据中删除{}:{}通过这样做,您正在为该对象分配一个空对象

What if you remove the "params" word from your angular http post call ? 如果您从有角度的http帖子呼叫中删除“ params”一词怎么办?

So the http post call is this instead 所以http post呼叫是这个

return this.http.post<Action[]>(this.apiURL + '/actions/launchactions', 
     {
        sessionId: action.sessionId,
        tag: action.actionTag,
        actionParams: action.actionParams
     })
    .pipe(
      retry(1),
      catchError(this.handleError)
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM