How to get specific data from a URL in Angular 2.0

I have a url like this:

https://example.com/?username1=Dr&Organization=Pepper&action=create

I need to display it in my browser inside a text box.

<input type="text" name="varname" value="Dr">

I need to get Drin my text box

+4
source share
2 answers

I assume that the endpoint of your URL will return JSON and try to use the returned data to populate your input value.

First import the HttpClientModule depending on your module:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then, from the inside, foo.component.tsyou can insert an instance of HttpClient into the constructor.

constructor(private http: HttpClient){
  }

Then you can use the specified HttpClientinstance httpas follows:

this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
      console.log(data);
    });
  }

(myProp), :

<input *ngIf="myProp" type="text" name="varname" value="myProp">

, *ngIF, , , myProp null undefined.


- -

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  name = null;


  constructor(private http: HttpClient){
  }

  ngOnInit(): void {
    this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
    // data = result: {name: 'Derek da Doctor'}
      this.name = data.result.name;
    });
  }
}

app.component.html

<input *ngIf="name" type="text" name="varname" value="{{name}}">
+2

url , :

id :

<input type="text" id="url" name="varname" value="Dr"/>

url:

document.getElementById("url").value = window.location.href;

url .

-1

Source: https://habr.com/ru/post/1692435/


All Articles