【问题标题】:Get param from URL with c# send to angular side使用 c# 从 URL 获取参数发送到 Angular 端
【发布时间】:2018-02-26 13:21:42
【问题描述】:

我想向我的应用程序的 url 发送一个可选参数以用作 我的一个文本框的占位符。我尝试了几种不同的 方法并且似乎无法让它们中的任何一个从 URL 获取参数 在我的 c# 代码中并将其传递给我的角度。任何帮助都会很大 感激不尽!

*我尝试使用 //import { ActivatedRoute, Params } from '@angular/router'; 但是,它一直给我这个问题。 (“没有激活路由的提供者”) 我可以不使用我宁愿从我的 c# 代码中获取它,这样我就可以 对其进行一些小的操作,然后将参数发送到我的角度,如果 可能。

C# 控制器

   [Route("api/[controller]")]
   public class PasswordController : Controller
   {
       private readonly AppSettings _options;

       public PasswordController(IOptions<AppSettings> optionsAccessor)
       {
           _options = optionsAccessor.Value;

       }

       /// <summary>
       /// Returns the ClientSettings object as a JSON string
       /// </summary>

       [HttpGet]
       public IActionResult Get([FromQuery]string emp)
       {
           //I get nothing on this...
           var x = HttpContext.Request.Query["emp"].ToString();
               Response.Headers.Add("x-emp-name", x);
           return Json(_options.ClientSettings);
       }

更改-pass.ts

import { Title } from '@angular/platform-browser';
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { MatSnackBar, MatDialog } from '@angular/material';
import { FormControl, FormGroup, Validators } from '@angular/forms';
//import { ActivatedRoute, Params } from '@angular/router';
import ViewOptions from '../models/view-options.model';
import Alerts from '../models/alerts.model';
import Recaptcha from '../models/recaptcha.model';
import ChangePasswordForm from '../models/change-password-form.model';
import Result from '../models/result-data.model';
import PasswordModel from '../models/password.model';
import DialogOverview from '../dialog/app.dialog'

import PasswordValidator from '../helpers/passwordValidator';
import PasswordStrength from '../helpers/passwordStrength';

import 'rxjs/add/operator/map';

const emailRegex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-
zA-Z0-9-]+)*$/;

@Component({
 selector: 'app-root',
 templateUrl: './change-password.html',
 styleUrls: ['./app.change-password.css']
})
export default class ChangePasswordComponent implements OnInit {
 // Form Controls
 FormGroup = new FormGroup({
   username: new FormControl('', [Validators.required, Validators.pattern
(emailRegex)]),
   currentPassword: new FormControl('', [Validators.required]),
   newPassword: new FormControl('', [Validators.required]),
   newPasswordVerify: new FormControl('', [Validators.required])
 }, PasswordValidator.MatchPassword);
 // Variables
 ViewOptions: ViewOptions;
 ResultData: Result;
 Loading: boolean = false;
 ErrorAlertMessage: string = '';
 FormData: PasswordModel;
 color: string = 'warn';
 value: number = 0;



 constructor(private http: Http, private snackBar: MatSnackBar,
   private titleService: Title, public dialog: MatDialog) {
   this.FormData = new PasswordModel;
   this.ViewOptions = new ViewOptions;
   this.ViewOptions.alerts = new Alerts;
   this.ViewOptions.recaptcha = new Recaptcha;
   this.ViewOptions.changePasswordForm = new ChangePasswordForm;

   this.FormGroup.valueChanges.subscribe(data => {
     if (data.newPassword != null)
       this.changeProgressBar(PasswordStrength.measureStrength
(data.newPassword));
   });
 }

 ngOnInit(): void {
    // If I set this it works needs to be dynamic and from the URL
    this.GetData("TestUser");
 }

private GetData(queryParam: string): void {
     this.FormData.Username = queryParam;
     this.http.get('api/password?emp='+ queryParam).subscribe(values => {
     this.ViewOptions = values.json();
     this.titleService.setTitle(this.ViewOptions.changePasswordTitle + " -
" + this.ViewOptions.applicationTitle);

     if (this.ViewOptions.recaptcha.isEnabled) {
       this.FormGroup.addControl('reCaptcha', new FormControl('',
[Validators.required]));
       const sp = document.createElement('script');
       sp.type = 'text/javascript';
       sp.async = true;
       sp.defer = true;
       sp.src =
'https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit&hl='
+ this.ViewOptions.recaptcha.languageCode;
     }
   });
 }

change-pass.html

                           <input matInput [(ngModel)]="FormData.Username"
formControlName="username" name="Username" type="email" required
placeholder="{{ViewOptions.changePasswordForm.usernamePlaceholder}}">

【问题讨论】:

    标签: c# asp.net angular asp.net-web-api


    【解决方案1】:

    试试下面的

    import {ActivatedRoute} from '@angular/router';
    ......
    export default class ChangePasswordComponent implements OnInit{
    .......
    //define the ActivatedRoute instance on your constructor
    constructor(.......
                 private route: ActivatedRoute)
    
    ........
     ngOnInit(){
      let paramValue;      
            this.route.queryParams.subscribe((params)=>{
       paramValue = params['paramName'];
    });
    
    console.log(paramValue); // this should contain your URL parameter       
    }
    .....
    }
    

    【讨论】:

    猜你喜欢
    • 2017-04-15
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多