angular learning(2)

152 阅读1分钟

使用服务

ng g component components/组件名

ng g service service/服务名

先在app.module.ts里面引入

import { StorageService } from './services/storage.service';

providers: [StorageService],

在用到的地方

import { StorageService } from './services/storage.service';

constructor(public storage: StorageService) {
    console.log(this.storage.get())

  }

子传父 viewChid获取节点

父中:
import { ViewChild } from '@angular/core';

@ViewChild('myBox') myBox:any

ngAfterViewInit(): void{
    console.log(this.myBox.nativeElement)
    this.myBox.nativeElement.style.width = '100px'
    this.myBox.nativeElement.style.height = '100px'
    this.myBox.nativeElement.style.background = 'red'
  }

  //#myBox给dom起了个别名
  <div #myBox>
  我是DOM节点
  </div>
  
  子无额外操作

父传子

子中:
import { Input } from '@angular/core';
@Input() title:any;
  @Input() msg:any;
  @Input() run:any;
  @Input() home:any;
  
  getParentrun(){
    this.run()
    this.home.run()
  }
  <h1>子组件获取父组件的值</h1>
  <div>{{title}}--{{msg}}</div>
  <h1>子组件获取父组件的方法</h1>
  <button (click)="getParentrun()">父组件的run方法</button>
  
父中:
  <app-header [title] = 'title' [msg]='msg' [run]="run" [home]="this"></app-header>

outer子父通信

ngOnChanges() 父子传值


service中:
import { Observable } from 'rxjs';
getRxjsData(){
    return new Observable((observer)=>{
      setTimeout(()=>{
        var name = 'mitty-rxjs';
        observer.next(name)
        // observer.error('出错用这个')

      },1000)
    })
  }


使用:
var rxjsData = this.storage.getRxjsData()
    rxjsData.subscribe((data)=>{
      console.log(data)
    })

使用get post方法

在app.module.tsimport { HttpClientModule } from '@angular/common/http'
imports: [
    HttpClientModule
  ]

在用到的地方
import { HttpClient } from '@angular/common/http'
constructor(public http:HttpClient) {

   }
   getData(){
    let api='http://a.itying.com/api/productlist'
    this.http.get(api).subscribe((response:any)=>{
      console.log(response)
      this.list = response.result
      console.log(this.list)
    })

  }
  
import { HttpClient, HttpHeaders} from '@angular/common/http'

postData(){
    const httpOptions = {headers: new HttpHeaders({ 'Content-Type': 'applicatio/json'})}
    let api = 'http://127.0.0.1:3000/dologin'
    this.http.post(api, {'username': 'mitty','age':18}, httpOptions).subscribe((response)=>{
      console.log(response)
    })

  }