typescript取下级值
interface resType {
data?: Object
}
export const baseApi = ({ method = 'get', headers = {}, params = {}, url = '', path = '' }) => {
let promise = new Promise((reslove, reject) => {
let option = {
url: path,
method,
timeout: 120000,
params,
headers
}
let options = (option as optionsType)
if (method === 'get') {
options.params = params
} else if (['post', 'put'].includes(method)) {
options.data = params
}
if ((<any>headers)['content-type']) {
(<any>headers)['content-type'] = 'application/x-www-form-urlencoded'
}
(<any>options).headers = headers || {}
axios(options)
.then((res: resType) => {
reslove(res.data)
})
.catch((err: any) => {
reject(err)
})
})
return promise
}
interface resLogin {
code?: number,
data?: object
}
const Login: React.FC<{}> = (props) => {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
let history = useHistory();
const onFinish = async (values: any) => {
console.log('Success:', values);
const { username, password } = values
let result = await userLogin({ params: { username, password } }) as resLogin
if(result.code === 200){
history.push("/layout");
}
};
.....
import React from 'react'
import axios from 'axios'
interface resType {
data?: Object
}
interface optionsType {
url?: string,
method?: string
timeout?: number,
params: object,
data?: object,
headers?: object
}
export const baseApi = ({ method = 'get', headers = {}, params = {}, url = '', path = '' }) => {
let promise = new Promise((reslove, reject) => {
let option = {
url: path,
method,
timeout: 120000
}
let options = option as optionsType
if (method === 'get') {
options.params = params
} else if (['post', 'put'].includes(method)) {
options.data = params
}
if ((<any>headers)['content-type']) {
(<any>headers)['content-type'] = 'application/x-www-form-urlencoded'
}
options.headers = headers || {}
axios(options)
.then((res: resType) => {
reslove(res.data)
})
.catch((err: any) => {
reject(err)
})
})
return promise
}